<!DOCTYPE HTML>
<html lang="zh-CN">


<head>
    <meta charset="utf-8">
    <meta name="keywords" content="锁, 博客 blog">
    <meta name="description" content="熊猫小二的博客  xmxe&#39;s blog">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
    <meta name="mobile-web-app-capable" content="yes">
    <meta name="format-detection" content="telephone=no">
    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
    <!-- 为了引用qq空间图床文件 -->
    <meta name="referrer" content="no-referrer">
    <!-- Global site tag (gtag.js) - Google Analytics -->


    <title>锁 | 熊猫小二</title>
    <link rel="icon" type="image/x-icon, image/vnd.microsoft.icon" href="/blog/favicon.ico">
    <link rel="stylesheet" type="text/css" href="/blog/libs/awesome/css/all.css">
    <link rel="stylesheet" type="text/css" href="/blog/libs/materialize/materialize.min.css">
    <link rel="stylesheet" type="text/css" href="/blog/libs/aos/aos.css">
    <link rel="stylesheet" type="text/css" href="/blog/libs/animate/animate.min.css">
    <link rel="stylesheet" type="text/css" href="/blog/libs/lightGallery/css/lightgallery.min.css">
    <link rel="stylesheet" type="text/css" href="/blog/css/matery.css">
    <link rel="stylesheet" type="text/css" href="/blog/css/my.css">
    <link rel="stylesheet" type="text/css" href="/blog/css/loading.css">

    <script src="/blog/libs/jquery/jquery.min.js"></script>

<meta name="generator" content="Hexo 6.3.0"></head>



   
<style>
    body{
       background-image: url(/blog/medias/cover.jpg);
       background-repeat:no-repeat;
       background-size:cover;
       background-attachment:fixed;
    }
</style>



<body>
    
  <div id="loading-box">
    <div class="loading-left-bg"></div>
    <div class="loading-right-bg"></div>
    <div class="spinner-box">
      <div class="configure-border-1">
        <div class="configure-core"></div>
      </div>
      <div class="configure-border-2">
        <div class="configure-core"></div>
      </div>
      <div class="loading-word">加载中...</div>
    </div>
  </div>
  <!-- 页面加载动画 -->
  <script>
    $(document).ready(function () {
      // document.body.style.overflow = 'auto';
      document.getElementById('loading-box').classList.add("loaded")
    })
  </script>

    <header class="navbar-fixed">
    <nav id="headNav" class="bg-color nav-transparent">
        <div id="navContainer" class="nav-wrapper container">
            <div class="brand-logo">
                <a href="/blog/" class="waves-effect waves-light">
                    
                        <img src="/blog/medias/logo.png" class="logo-img" alt="LOGO">
                    
                    <span class="logo-span">熊猫小二</span>
                </a>
            </div>
            

<a href="#" data-target="mobile-nav" class="sidenav-trigger button-collapse"><i class="fas fa-bars"></i></a>
<ul class="right nav-menu">
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/blog/" class="waves-effect waves-light">
      
      <i class="fas fa-home" style="zoom: 0.6;"></i>
      
      <span>首页</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="#" class="waves-effect waves-light">

      
      <i class="fas fa-book" style="zoom: 0.6;"></i>
      
      <span>归档</span>
      <i class="fas fa-chevron-down" aria-hidden="true" style="zoom: 0.6;"></i>
    </a>
    <ul class="sub-nav menus_item_child ">
      
      <li>
        <a href="/blog/archives">
          
          <i class="fas fa-archive" style="margin-top: -20px; zoom: 0.6;"></i>
          
          <span>归档</span>
        </a>
      </li>
      
      <li>
        <a href="/blog/tags">
          
          <i class="fas fa-tags" style="margin-top: -20px; zoom: 0.6;"></i>
          
          <span>标签</span>
        </a>
      </li>
      
      <li>
        <a href="/blog/categories">
          
          <i class="fas fa-bookmark" style="margin-top: -20px; zoom: 0.6;"></i>
          
          <span>分类</span>
        </a>
      </li>
      
    </ul>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/blog/friends" class="waves-effect waves-light">
      
      <i class="fas fa-address-book" style="zoom: 0.6;"></i>
      
      <span>友链</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="#" class="waves-effect waves-light">

      
      <i class="fas fa-user-circle" style="zoom: 0.6;"></i>
      
      <span>关于</span>
      <i class="fas fa-chevron-down" aria-hidden="true" style="zoom: 0.6;"></i>
    </a>
    <ul class="sub-nav menus_item_child ">
      
      <li>
        <a href="/blog/about">
          
          <i class="fas fa-star-of-david" style="margin-top: -20px; zoom: 0.6;"></i>
          
          <span>主页</span>
        </a>
      </li>
      
      <li>
        <a href="/blog/gallery">
          
          <i class="fas fa-images" style="margin-top: -20px; zoom: 0.6;"></i>
          
          <span>相册</span>
        </a>
      </li>
      
    </ul>
    
  </li>
  
  <li>
    <a href="#searchModal" class="modal-trigger waves-effect waves-light">
      <i id="searchIcon" class="fas fa-search" title="搜索" style="zoom: 0.85;"></i>
    </a>
  </li>
  
    <li>
      <a class="waves-effect waves-light" onclick="switchNightMode()">
        <i id="sum-moon-icon" class="fas fa-sun" style="zoom:0.65;" title="切换主题"></i>
      </a>
    </li>
  
  
</ul>


<div id="mobile-nav" class="side-nav sidenav">

    <div class="mobile-head bg-color">
        
          <img src="/blog/medias/logo.png" class="logo-img circle responsive-img">
        
        <div class="logo-name">熊猫小二</div>
        <div class="logo-desc">
            
            熊猫小二的博客  xmxe&#39;s blog
            
        </div>
    </div>

    

    <ul class="menu-list mobile-menu-list">
        
        <li class="m-nav-item">
	  
		<a href="/blog/" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-home"></i>
			
			首页
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="javascript:;">
			
				<i class="fa-fw fas fa-book"></i>
			
			归档
			<span class="m-icon"><i class="fas fa-chevron-right"></i></span>
		</a>
            <ul  >
              
                <li>

                  <a href="/blog/archives " style="margin-left:75px">
				  
				   <i class="fa fas fa-archive" style="position: absolute;left:50px" ></i>
			      
		          <span>归档</span>
                  </a>
                </li>
              
                <li>

                  <a href="/blog/tags " style="margin-left:75px">
				  
				   <i class="fa fas fa-tags" style="position: absolute;left:50px" ></i>
			      
		          <span>标签</span>
                  </a>
                </li>
              
                <li>

                  <a href="/blog/categories " style="margin-left:75px">
				  
				   <i class="fa fas fa-bookmark" style="position: absolute;left:50px" ></i>
			      
		          <span>分类</span>
                  </a>
                </li>
              
            </ul>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/blog/friends" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-address-book"></i>
			
			友链
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="javascript:;">
			
				<i class="fa-fw fas fa-user-circle"></i>
			
			关于
			<span class="m-icon"><i class="fas fa-chevron-right"></i></span>
		</a>
            <ul  >
              
                <li>

                  <a href="/blog/about " style="margin-left:75px">
				  
				   <i class="fa fas fa-star-of-david" style="position: absolute;left:50px" ></i>
			      
		          <span>主页</span>
                  </a>
                </li>
              
                <li>

                  <a href="/blog/gallery " style="margin-left:75px">
				  
				   <i class="fa fas fa-images" style="position: absolute;left:50px" ></i>
			      
		          <span>相册</span>
                  </a>
                </li>
              
            </ul>
          
        </li>
        
        
    </ul>
</div>


        </div>

        
    </nav>

</header>

    
<script src="/blog/libs/cryptojs/crypto-js.min.js"></script>
<script>
    (function() {
        let pwd = '';
        if (pwd && pwd.length > 0) {
            if (pwd !== CryptoJS.SHA256(prompt('请输入访问本文章的密码')).toString(CryptoJS.enc.Hex)) {
                alert('密码错误，将返回主页！');
                location.href = '/blog/';
            }
        }
    })();
</script>




<div class="bg-cover pd-header post-cover" style="background-image: url('/blog/medias/featureimages/0.jpg')">
    <div class="container" style="right: 0px;left: 0px;">
        <div class="row">
            <div class="col s12 m12 l12">
                <div class="brand">
                    <h1 id="post-title" class="description center-align post-title"></h1>

                    
                        <!-- <script src="https://cdn.jsdelivr.net/npm/typed.js@2.0.11"></script> -->
                        <script>
                            var typedObj = new Typed("#post-title", {
                                strings: [ '锁' ],
                                startDelay: 300,
                                typeSpeed: 70,
                                loop: false,
                                backSpeed: 50,
                                showCursor: true
                            });
                        </script>
                    
                </div>
            </div>
        </div>
    </div>
</div>




<main class="post-container content">

    
    <link rel="stylesheet" href="/blog/libs/tocbot/tocbot.css">
<style>
    #articleContent h1::before,
    #articleContent h2::before,
    #articleContent h3::before,
    #articleContent h4::before,
    #articleContent h5::before,
    #articleContent h6::before {
        display: block;
        content: " ";
        height: 100px;
        margin-top: -100px;
        visibility: hidden;
    }

    #articleContent :focus {
        outline: none;
    }

    .toc-fixed {
        position: fixed;
        top: 64px;
    }

    .toc-widget {
        width: 345px;
        padding-left: 20px;
        background-color: rgb(255, 255, 255,0.7);
        border-radius: 10px;
        box-shadow: 0 10px 35px 2px rgba(0, 0, 0, .15), 0 5px 15px rgba(0, 0, 0, .07), 0 2px 5px -5px rgba(0, 0, 0, .1) !important;
    }

    .toc-widget .toc-title {
        padding: 35px 0 15px 17px;
        font-size: 1.5rem;
        font-weight: bold;
        line-height: 1.5rem;
    }

    .toc-widget ol {
        padding: 0;
        list-style: none;
    }

    #toc-content {
        padding-bottom: 30px;
        overflow: auto;
        max-height: 480px;
    }

    #toc-content ol {
        padding-left: 10px;
    }

    #toc-content ol li {
        padding-left: 10px;
    }

    #toc-content .toc-link:hover {
        color: #42b983;
        font-weight: 700;
        text-decoration: underline;
    }

    #toc-content .toc-link::before {
        background-color: transparent;
        max-height: 25px;

        position: absolute;
        right: 23.5vw;
        display: block;
    }

    #toc-content .is-active-link {
        color: #42b983;
    }

    #floating-toc-btn {
        position: fixed;
        right: 15px;
        bottom: 76px;
        padding-top: 15px;
        margin-bottom: 0;
        z-index: 998;
    }

    #floating-toc-btn .btn-floating {
        width: 48px;
        height: 48px;
    }

    #floating-toc-btn .btn-floating i {
        line-height: 48px;
        font-size: 1.4rem;
    }
</style>
<div class="row">
    <div id="main-content" class="col s12 m12 l9">
        <!-- 文章内容详情 -->
<div id="artDetail">
    <div class="card">
        <div class="card-content article-info">
            <div class="row tag-cate">
                <div class="col s7">
                    
                          <div class="article-tag">
                            <span class="chip bg-color">无标签</span>
                          </div>
                    
                </div>
                <div class="col s5 right-align">
                    
                    <div class="post-cate">
                        <i class="fas fa-bookmark fa-fw icon-category"></i>
                        
                            <a href="/blog/categories/Java/" class="post-category">
                                Java
                            </a>
                        
                    </div>
                    
                </div>
            </div>

            <div class="post-info">
                

                

                

                

                
            </div>
        </div>
        <hr class="clearfix">

        
        <!-- 是否加载使用自带的 prismjs. -->
        <link rel="stylesheet" href="/blog/libs/prism/prism.css">
        

        
        <!-- 代码块折行 -->
        <style type="text/css">
            code[class*="language-"], pre[class*="language-"] { white-space: pre-wrap !important; }
        </style>
        

        <div class="card-content article-card-content">
            <div id="articleContent">
                <h2 id="悲观锁"><a href="#悲观锁" class="headerlink" title="悲观锁"></a>悲观锁</h2><p>悲观锁总是假设最坏的情况，认为共享资源每次被访问的时候就会出现问题(比如共享数据被修改)，所以每次在获取资源操作的时候都会上锁，这样其他线程想拿到这个资源就会阻塞直到锁被上一个持有者释放。也就是说，<strong>共享资源每次只给一个线程使用，其它线程阻塞，用完后再把资源转让给其它线程</strong>。像Java中synchronized和ReentrantLock等独占锁就是悲观锁思想的实现。<strong>悲观锁通常多用于写比较多的情况下（多写场景），避免频繁失败和重试影响性能</strong>。悲观锁适用于数据库高并发的大量写入操作，本次事务提交之前（事务提交时会释放事务过程中的锁），外界无法修改这些记录。具体使用:mysql数据库首先要设置事务不允许自动提交<code>set autocommit=0</code>然后<code>select name from table where id = ? for update</code>将查询的结果上锁,这样的话其他得事务查询的话如果不加for update能够正常查询，否则会一直显示正在查询中 并且其他事务不可以对此数据做增删改操作,当上锁的查询语句的事务提交后，即执行commit后其他事务才可以对数据进行其他的操作。悲观锁可以避免冲突的发生，但是会降低效率。<br><strong>如果查询条件用了索引&#x2F;主键，那么select ….. for update就会进行锁行。</strong><br><strong>如果是普通字段(没有索引&#x2F;主键)，那么select ….. for update就会进行锁表。</strong></p>
<h2 id="乐观锁"><a href="#乐观锁" class="headerlink" title="乐观锁"></a>乐观锁</h2><p><strong>乐观锁实现</strong></p>
<p>乐观锁总是假设最好的情况，认为共享资源每次被访问的时候不会出现问题，线程可以不停地执行，无需加锁也无需等待，只是在提交修改的时候去验证对应的资源（也就是数据）是否被其它线程修改了（具体方法可以使用版本号机制或CAS算法）。在Java中<code>java.util.concurrent.atomic</code>包下面的原子变量类就是使用了乐观锁的一种实现方式<strong>CAS</strong>实现的。<strong>乐观锁通常多于写比较少的情况下（多读场景），避免频繁加锁影响性能，大大提升了系统的吞吐量。</strong></p>
<p>乐观锁大多是基于数据版本(Version)记录机制实现。何谓数据版本？即为数据增加一个版本标识，在基于数据库表的版本解决方案中，一般是通过为数据库表增加一个“version”字段来实现。读取出数据时，将此版本号一同读出，之后更新时，对此版本号加一。此时，将提交数据的版本数据与数据库表对应记录的当前版本信息进行比对，如果提交的数据版本号大于数据库表当前版本号，则予以更新，否则认为是过期数据。对于上面修改用户帐户信息的例子而言，假设数据库中帐户信息表中有一个version字段，当前值为1；而当前帐户余额字段（balance）为$100。操作员A此时将其读出（version&#x3D;1），并从其帐户余额中扣除$50（$100-$50）。2在操作员A操作的过程中，操作员B也读入此用户信息（version&#x3D;1），并从其帐户余额中扣除$20（$100-$20）。3操作员A完成了修改工作，将数据版本号加一（version&#x3D;2），连同帐户扣除后余额（balance&#x3D;$50），提交至数据库更新，此时由于提交数据版本大于数据库记录当前版本，数据被更新，数据库记录version更新为2。4操作员B完成了操作，也将版本号加一（version&#x3D;2）试图向数据库提交数据（balance&#x3D;$80），但此时比对数据库记录版本时发现，操作员B提交的数据版本号为2，数据库记录当前版本也为2，不满足“提交版本必须大于记录当前版本才能执行更新“的乐观锁策略，因此，操作员B的提交被驳回。这样，就避免了操作员B用基于version&#x3D;1的旧数据修改的结果覆盖操作员A的操作结果的可能。从上面的例子可以看出，乐观锁机制避免了长事务中的数据库加锁开销（操作员A和操作员B操作过程中，都没有对数据库数据加锁），大大提升了大并发量下的系统整体性能表现。需要注意的是，乐观锁机制往往基于系统中的数据存储逻辑，因此也具备一定的局限性，如在上例中，由于乐观锁机制是在我们的系统中实现，来自外部系统的用户余额更新操作不受我们系统的控制，因此可能会造成脏数据被更新到数据库中。在系统设计阶段，我们应该充分考虑到这些情况出现的可能性，并进行相应调整（如将乐观锁策略在数据库存储过程中实现，对外只开放基于此存储过程的数据更新途径，而不是将数据库表直接对外公开）</p>
<pre class="line-numbers language-sql" data-language="sql"><code class="language-sql"><span class="token keyword">update</span> <span class="token keyword">table</span> <span class="token keyword">set</span> <span class="token keyword">status</span><span class="token operator">=</span><span class="token comment">#&#123;status&#125;,name=#&#123;name&#125;,version=version+1 where id=#&#123;id&#125; and version=#&#123;version&#125;</span><span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre>

<p><strong>乐观锁存在哪些问题</strong></p>
<p><strong>1. ABA问题</strong></p>
<p>如果一个变量V初次读取的时候是A值，并且在准备赋值的时候检查到它仍然是A值，那我们就能说明它的值没有被其他线程修改过了吗？很明显是不能的，因为在这段时间它的值可能被改为其他值，然后又改回A，那CAS操作就会误认为它从来没有被修改过。这个问题被称为CAS操作的<strong>ABA问题</strong>。ABA问题的解决思路是在变量前面追加上<strong>版本号或者时间戳</strong>。JDK1.5以后的AtomicStampedReference类就是用来解决ABA问题的，其中的compareAndSet()方法就是首先检查当前引用是否等于预期引用，并且当前标志是否等于预期标志，如果全部相等，则以原子方式将该引用和该标志的值设置为给定的更新值。</p>
<pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token keyword">public</span> <span class="token keyword">boolean</span> <span class="token function">compareAndSet</span><span class="token punctuation">(</span><span class="token class-name">V</span>   expectedReference<span class="token punctuation">,</span>
                             <span class="token class-name">V</span>   newReference<span class="token punctuation">,</span>
                             <span class="token keyword">int</span> expectedStamp<span class="token punctuation">,</span>
                             <span class="token keyword">int</span> newStamp<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
    <span class="token class-name">Pair</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token class-name">V</span><span class="token punctuation">></span></span> current <span class="token operator">=</span> pair<span class="token punctuation">;</span>
    <span class="token keyword">return</span>
        expectedReference <span class="token operator">==</span> current<span class="token punctuation">.</span>reference <span class="token operator">&amp;&amp;</span>
        expectedStamp <span class="token operator">==</span> current<span class="token punctuation">.</span>stamp <span class="token operator">&amp;&amp;</span>
        <span class="token punctuation">(</span><span class="token punctuation">(</span>newReference <span class="token operator">==</span> current<span class="token punctuation">.</span>reference <span class="token operator">&amp;&amp;</span>
          newStamp <span class="token operator">==</span> current<span class="token punctuation">.</span>stamp<span class="token punctuation">)</span> <span class="token operator">||</span>
         <span class="token function">casPair</span><span class="token punctuation">(</span>current<span class="token punctuation">,</span> <span class="token class-name">Pair</span><span class="token punctuation">.</span><span class="token function">of</span><span class="token punctuation">(</span>newReference<span class="token punctuation">,</span> newStamp<span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token punctuation">&#125;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<p><strong>2. 循环时间长开销大</strong></p>
<p>CAS经常会用到自旋操作来进行重试，也就是不成功就一直循环执行直到成功。如果长时间不成功，会给CPU带来非常大的执行开销。如果JVM能支持处理器提供的pause指令那么效率会有一定的提升，pause指令有两个作用：</p>
<ol>
<li>可以延迟流水线执行指令，使CPU不会消耗过多的执行资源，延迟的时间取决于具体实现的版本，在一些处理器上延迟时间是零。</li>
<li>可以避免在退出循环的时候因内存顺序冲而引起CPU流水线被清空，从而提高CPU的执行效率。</li>
</ol>
<p><strong>3. 只能保证一个共享变量的原子操作</strong></p>
<p>CAS只对单个共享变量有效，当操作涉及跨多个共享变量时CAS无效。但是从JDK1.5开始，提供了<strong>AtomicReference</strong>类来保证引用对象之间的原子性，你可以把多个变量放在一个对象里来进行CAS操作.所以我们可以使用锁或者利用<strong>AtomicReference</strong>类把多个共享变量合并成一个共享变量来操作。</p>
<h2 id="分布式锁"><a href="#分布式锁" class="headerlink" title="分布式锁"></a>分布式锁</h2><p><strong>分布式锁介绍</strong></p>
<p>对于单机多线程来说，在Java中，我们通常使用ReetrantLock类、synchronized关键字这类JDK自带的本地锁来控制一个JVM进程内的多个线程对本地共享资源的访问。这些线程访问共享资源是互斥的，同一时刻只有一个线程可以获取到本地锁访问共享资源。分布式系统下，不同的服务&#x2F;客户端通常运行在独立的JVM进程上。如果多个JVM进程共享同一份资源的话，使用本地锁就没办法实现资源的互斥访问了。于是，分布式锁就诞生了。举个例子：系统的订单服务一共部署了3份，都对外提供服务。用户下订单之前需要检查库存，为了防止超卖，这里需要加锁以实现对检查库存操作的同步访问。由于订单服务位于不同的JVM进程中，本地锁在这种情况下就没办法正常工作了。我们需要用到分布式锁，这样的话，即使多个线程不在同一个JVM进程中也能获取到同一把锁，进而实现共享资源的互斥访问。这些独立的进程中的线程访问共享资源是互斥的，同一时刻只有一个线程可以获取到分布式锁访问共享资源。一个最基本的分布式锁需要满足：</p>
<ul>
<li><strong>互斥</strong>：任意一个时刻，锁只能被一个线程持有；</li>
<li><strong>高可用</strong>：锁服务是高可用的。并且，即使客户端的释放锁的代码逻辑出现问题，锁最终一定还是会被释放，不会影响其他线程对共享资源的访问。</li>
<li><strong>可重入</strong>：一个节点获取了锁之后，还可以再次获取锁。</li>
</ul>
<p>通常情况下，我们一般会选择基于Redis或者ZooKeeper实现分布式锁，Redis用的要更多一点，我这里也以Redis为例介绍分布式锁的实现。</p>
<h3 id="基于Redis实现分布式锁"><a href="#基于Redis实现分布式锁" class="headerlink" title="基于Redis实现分布式锁"></a>基于Redis实现分布式锁</h3><p><strong>如何基于Redis实现一个最简易的分布式锁？</strong></p>
<p>不论是本地锁还是分布式锁，核心都在于“互斥”。在Redis中，<code>SETNX</code>命令是可以帮助我们实现互斥。<code>SETNX</code>即<strong>SET if Not Exists</strong>(对应Java中的<code>setIfAbsent</code>方法)，如果key不存在的话，才会设置key的值。如果key已经存在，<code>SETNX</code>啥也不做。</p>
<pre class="line-numbers language-bash" data-language="bash"><code class="language-bash"><span class="token operator">></span> SETNX lockKey uniqueValue
<span class="token punctuation">(</span>integer<span class="token punctuation">)</span> <span class="token number">1</span>
<span class="token operator">></span> SETNX lockKey uniqueValue
<span class="token punctuation">(</span>integer<span class="token punctuation">)</span> <span class="token number">0</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span></span></code></pre>

<p>释放锁的话，直接通过<code>DEL</code>命令删除对应的key即可。</p>
<pre class="line-numbers language-bash" data-language="bash"><code class="language-bash"><span class="token operator">></span> DEL lockKey
<span class="token punctuation">(</span>integer<span class="token punctuation">)</span> <span class="token number">1</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span></span></code></pre>

<p>为了防止误删到其他的锁，这里我们建议使用Lua脚本通过key对应的value（唯一值）来判断。选用Lua脚本是为了保证解锁操作的原子性。因为Redis在执行Lua脚本时，可以以原子性的方式执行，从而保证了锁释放操作的原子性。</p>
<pre class="line-numbers language-lua" data-language="lua"><code class="language-lua"><span class="token operator">//</span> 释放锁时，先比较锁对应的value值是否相等，避免锁的误释放
<span class="token keyword">if</span> redis<span class="token punctuation">.</span><span class="token function">call</span><span class="token punctuation">(</span><span class="token string">"get"</span><span class="token punctuation">,</span>KEYS<span class="token punctuation">[</span><span class="token number">1</span><span class="token punctuation">]</span><span class="token punctuation">)</span> <span class="token operator">==</span> ARGV<span class="token punctuation">[</span><span class="token number">1</span><span class="token punctuation">]</span> <span class="token keyword">then</span>
    <span class="token keyword">return</span> redis<span class="token punctuation">.</span><span class="token function">call</span><span class="token punctuation">(</span><span class="token string">"del"</span><span class="token punctuation">,</span>KEYS<span class="token punctuation">[</span><span class="token number">1</span><span class="token punctuation">]</span><span class="token punctuation">)</span>
<span class="token keyword">else</span>
    <span class="token keyword">return</span> <span class="token number">0</span>
<span class="token keyword">end</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<p>这是一种最简易的Redis分布式锁实现，实现方式比较简单，性能也很高效。不过，这种方式实现分布式锁存在一些问题。就比如应用程序遇到一些问题比如释放锁的逻辑突然挂掉，可能会导致锁无法被释放，进而造成共享资源无法再被其他线程&#x2F;进程访问。</p>
<p><strong>为什么要给锁设置一个过期时间？</strong></p>
<p>为了避免锁无法被释放，我们可以想到的一个解决办法就是：给这个key（也就是锁）设置一个过期时间。</p>
<pre class="line-numbers language-bash" data-language="bash"><code class="language-bash"><span class="token number">127.0</span>.0.1:637<span class="token operator"><span class="token file-descriptor important">9</span>></span> SET lockKey uniqueValue EX <span class="token number">3</span> NX
OK<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span></span></code></pre>

<ul>
<li><strong>lockKey</strong>：加锁的锁名；</li>
<li><strong>uniqueValue</strong>：能够唯一标示锁的随机字符串；</li>
<li><strong>NX</strong>：只有当lockKey对应的key值不存在的时候才能SET成功；</li>
<li><strong>EX</strong>：过期时间设置（秒为单位）EX3标示这个锁有一个3秒的自动过期时间。与EX对应的是PX（毫秒为单位），这两个都是过期时间设置。</li>
</ul>
<p>一定要保证设置指定key的值和过期时间是一个原子操作!!不然的话，依然可能会出现锁无法被释放的问题。这样确实可以解决问题，不过，这种解决办法同样存在漏洞：如果操作共享资源的时间大于过期时间，就会出现锁提前过期的问题，进而导致分布式锁直接失效。如果锁的超时时间设置过长，又会影响到性能。你或许在想：如果操作共享资源的操作还未完成，锁过期时间能够自己续期就好了！</p>
<p><strong>如何实现锁的优雅续期？</strong></p>
<p>对于Java开发的小伙伴来说，已经有了现成的解决方案：<a target="_blank" rel="noopener" href="https://github.com/redisson/redisson">Redisson</a>。其他语言的解决方案，可以在<a target="_blank" rel="noopener" href="https://redis.io/topics/distlock">Redis官方文档</a>中找到</p>
<p><img src="https://guide-blog-images.oss-cn-shenzhen.aliyuncs.com/github/javaguide/redis-distributed-lock.png" alt="DistributedlockswithRedis"></p>
<p>Redisson是一个开源的Java语言Redis客户端，提供了很多开箱即用的功能，不仅仅包括多种分布式锁的实现。并且，Redisson还支持Redis单机、RedisSentinel、RedisCluster等多种部署架构。Redisson中的分布式锁自带自动续期机制，使用起来非常简单，原理也比较简单，其提供了一个专门用来监控和续期锁的<strong>WatchDog（看门狗）</strong>，如果操作共享资源的线程还未执行完成的话，WatchDog会不断地延长锁的过期时间，进而保证锁不会因为超时而被释放。看门狗名字的由来于<code>getLockWatchdogTimeout()</code>方法，这个方法返回的是看门狗给锁续期的过期时间，默认为30秒（<a target="_blank" rel="noopener" href="https://github.com/redisson/redisson/releases/tag/redisson-3.17.6">redisson-3.17.6</a>）。</p>
<pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token comment">// 默认30秒，支持修改</span>
<span class="token keyword">private</span> <span class="token keyword">long</span> lockWatchdogTimeout <span class="token operator">=</span> <span class="token number">30</span> <span class="token operator">*</span> <span class="token number">1000</span><span class="token punctuation">;</span>

<span class="token keyword">public</span> <span class="token class-name">Config</span> <span class="token function">setLockWatchdogTimeout</span><span class="token punctuation">(</span><span class="token keyword">long</span> lockWatchdogTimeout<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
    <span class="token keyword">this</span><span class="token punctuation">.</span>lockWatchdogTimeout <span class="token operator">=</span> lockWatchdogTimeout<span class="token punctuation">;</span>
    <span class="token keyword">return</span> <span class="token keyword">this</span><span class="token punctuation">;</span>
<span class="token punctuation">&#125;</span>
<span class="token keyword">public</span> <span class="token keyword">long</span> <span class="token function">getLockWatchdogTimeout</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
  	<span class="token keyword">return</span> lockWatchdogTimeout<span class="token punctuation">;</span>
<span class="token punctuation">&#125;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<p><code>renewExpiration()</code>方法包含了看门狗的主要逻辑：</p>
<pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token keyword">private</span> <span class="token keyword">void</span> <span class="token function">renewExpiration</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
         <span class="token comment">//......</span>
        <span class="token class-name">Timeout</span> task <span class="token operator">=</span> commandExecutor<span class="token punctuation">.</span><span class="token function">getConnectionManager</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">newTimeout</span><span class="token punctuation">(</span><span class="token keyword">new</span> <span class="token class-name">TimerTask</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
            <span class="token annotation punctuation">@Override</span>
            <span class="token keyword">public</span> <span class="token keyword">void</span> <span class="token function">run</span><span class="token punctuation">(</span><span class="token class-name">Timeout</span> timeout<span class="token punctuation">)</span> <span class="token keyword">throws</span> <span class="token class-name">Exception</span> <span class="token punctuation">&#123;</span>
                <span class="token comment">//......</span>
                <span class="token comment">// 异步续期，基于Lua脚本</span>
                <span class="token class-name">CompletionStage</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token class-name">Boolean</span><span class="token punctuation">></span></span> future <span class="token operator">=</span> <span class="token function">renewExpirationAsync</span><span class="token punctuation">(</span>threadId<span class="token punctuation">)</span><span class="token punctuation">;</span>
                future<span class="token punctuation">.</span><span class="token function">whenComplete</span><span class="token punctuation">(</span><span class="token punctuation">(</span>res<span class="token punctuation">,</span> e<span class="token punctuation">)</span> <span class="token operator">-></span> <span class="token punctuation">&#123;</span>
                    <span class="token keyword">if</span> <span class="token punctuation">(</span>e <span class="token operator">!=</span> <span class="token keyword">null</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
                        <span class="token comment">// 无法续期</span>
                        log<span class="token punctuation">.</span><span class="token function">error</span><span class="token punctuation">(</span><span class="token string">"Can't update lock "</span> <span class="token operator">+</span> <span class="token function">getRawName</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator">+</span> <span class="token string">" expiration"</span><span class="token punctuation">,</span> e<span class="token punctuation">)</span><span class="token punctuation">;</span>
                        <span class="token constant">EXPIRATION_RENEWAL_MAP</span><span class="token punctuation">.</span><span class="token function">remove</span><span class="token punctuation">(</span><span class="token function">getEntryName</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
                        <span class="token keyword">return</span><span class="token punctuation">;</span>
                    <span class="token punctuation">&#125;</span>

                    <span class="token keyword">if</span> <span class="token punctuation">(</span>res<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
                        <span class="token comment">// 递归调用实现续期</span>
                        <span class="token function">renewExpiration</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
                    <span class="token punctuation">&#125;</span> <span class="token keyword">else</span> <span class="token punctuation">&#123;</span>
                        <span class="token comment">// 取消续期</span>
                        <span class="token function">cancelExpirationRenewal</span><span class="token punctuation">(</span><span class="token keyword">null</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
                    <span class="token punctuation">&#125;</span>
                <span class="token punctuation">&#125;</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
            <span class="token punctuation">&#125;</span>
         <span class="token comment">// 延迟internalLockLeaseTime/3（默认10s，也就是30/3）再调用</span>
        <span class="token punctuation">&#125;</span><span class="token punctuation">,</span> internalLockLeaseTime <span class="token operator">/</span> <span class="token number">3</span><span class="token punctuation">,</span> <span class="token class-name">TimeUnit</span><span class="token punctuation">.</span><span class="token constant">MILLISECONDS</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

        ee<span class="token punctuation">.</span><span class="token function">setTimeout</span><span class="token punctuation">(</span>task<span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token punctuation">&#125;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<p>默认情况下，每过10秒，看门狗就会执行续期操作，将锁的超时时间设置为30秒。看门狗续期前也会先判断是否需要执行续期操作，需要才会执行续期，否则取消续期操作。WatchDog通过调用<code>renewExpirationAsync()</code>方法实现锁的异步续期：</p>
<pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token keyword">protected</span> <span class="token class-name">CompletionStage</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token class-name">Boolean</span><span class="token punctuation">></span></span> <span class="token function">renewExpirationAsync</span><span class="token punctuation">(</span><span class="token keyword">long</span> threadId<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
    <span class="token keyword">return</span> <span class="token function">evalWriteAsync</span><span class="token punctuation">(</span><span class="token function">getRawName</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">,</span> <span class="token class-name">LongCodec</span><span class="token punctuation">.</span><span class="token constant">INSTANCE</span><span class="token punctuation">,</span> <span class="token class-name">RedisCommands</span><span class="token punctuation">.</span><span class="token constant">EVAL_BOOLEAN</span><span class="token punctuation">,</span>
            <span class="token comment">// 判断是否为持锁线程，如果是就执行续期操作，就锁的过期时间设置为30s（默认）</span>
            <span class="token string">"if (redis.call('hexists', KEYS[1], ARGV[2]) == 1) then "</span> <span class="token operator">+</span>
                    <span class="token string">"redis.call('pexpire', KEYS[1], ARGV[1]); "</span> <span class="token operator">+</span>
                    <span class="token string">"return 1; "</span> <span class="token operator">+</span>
                    <span class="token string">"end; "</span> <span class="token operator">+</span>
                    <span class="token string">"return 0;"</span><span class="token punctuation">,</span>
            <span class="token class-name">Collections</span><span class="token punctuation">.</span><span class="token function">singletonList</span><span class="token punctuation">(</span><span class="token function">getRawName</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">,</span>
            internalLockLeaseTime<span class="token punctuation">,</span> <span class="token function">getLockName</span><span class="token punctuation">(</span>threadId<span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token punctuation">&#125;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<p>可以看出，<code>renewExpirationAsync</code>方法其实是调用Lua脚本实现的续期，这样做主要是为了保证续期操作的原子性。这里以Redisson的分布式可重入锁<code>RLock</code>为例来说明如何使用Redisson实现分布式锁：</p>
<pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token comment">// 1.获取指定的分布式锁对象</span>
<span class="token class-name">RLock</span> lock <span class="token operator">=</span> redisson<span class="token punctuation">.</span><span class="token function">getLock</span><span class="token punctuation">(</span><span class="token string">"lock"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token comment">// 2.拿锁且不设置锁超时时间，具备Watch Dog自动续期机制</span>
lock<span class="token punctuation">.</span><span class="token function">lock</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token comment">// 3.执行业务</span>
<span class="token punctuation">.</span><span class="token punctuation">.</span><span class="token punctuation">.</span>
<span class="token comment">// 4.释放锁</span>
lock<span class="token punctuation">.</span><span class="token function">unlock</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<p>只有未指定锁超时时间，才会使用到Watch Dog自动续期机制。</p>
<pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token comment">// 手动给锁设置过期时间，不具备Watch Dog自动续期机制</span>
lock<span class="token punctuation">.</span><span class="token function">lock</span><span class="token punctuation">(</span><span class="token number">10</span><span class="token punctuation">,</span> <span class="token class-name">TimeUnit</span><span class="token punctuation">.</span><span class="token constant">SECONDS</span><span class="token punctuation">)</span><span class="token punctuation">;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span></span></code></pre>

<p>如果使用Redis来实现分布式锁的话，还是比较推荐直接基于Redisson来做的。</p>
<p><strong>如何实现可重入锁？</strong></p>
<p>所谓可重入锁指的是在一个线程中可以多次获取同一把锁，比如一个线程在执行一个带锁的方法，该方法中又调用了另一个需要相同锁的方法，则该线程可以直接执行调用的方法即可重入，而无需重新获得锁。像Java中的synchronized和ReentrantLock都属于可重入锁。<strong>不可重入的分布式锁基本可以满足绝大部分业务场景了，一些特殊的场景可能会需要使用可重入的分布式锁</strong>。可重入分布式锁的实现核心思路是线程在获取锁的时候判断是否为自己的锁，如果是的话，就不用再重新获取了。为此，我们可以为每个锁关联一个可重入计数器和一个占有它的线程。当可重入计数器大于0时，则锁被占有，需要判断占有该锁的线程和请求获取锁的线程是否为同一个。实际项目中，我们不需要自己手动实现，推荐使用我们上面提到的<strong>Redisson</strong>，其内置了多种类型的锁比如可重入锁（ReentrantLock）、自旋锁（SpinLock）、公平锁（FairLock）、多重锁（MultiLock）、红锁（RedLock）、读写锁（ReadWriteLock）。</p>
<p><strong>Redis如何解决集群情况下分布式锁的可靠性？</strong></p>
<p>为了避免单点故障，生产环境下的Redis服务通常是集群化部署的。Redis集群下，上面介绍到的分布式锁的实现会存在一些问题。由于Redis集群数据同步到各个节点时是异步的，如果在Redis主节点获取到锁后，在没有同步到其他节点时，Redis主节点宕机了，此时新的Redis主节点依然可以获取锁，所以多个应用服务就可以同时获取到锁。针对这个问题，Redis之父antirez设计了<a target="_blank" rel="noopener" href="https://redis.io/topics/distlock">Redlock算法</a>来解决。Redlock算法的思想是让客户端向Redis集群中的多个独立的Redis实例依次请求申请加锁，如果客户端能够和半数以上的实例成功地完成加锁操作，那么我们就认为，客户端成功地获得分布式锁，否则加锁失败。即使部分Redis节点出现问题，只要保证Redis集群中有半数以上的Redis节点可用，分布式锁服务就是正常的。Redlock是直接操作Redis节点的，并不是通过Redis集群操作的，这样才可以避免Redis集群主从切换导致的锁丢失问题。Redlock实现比较复杂，性能比较差，发生时钟变迁的情况下还存在安全性隐患。《数据密集型应用系统设计》一书的作者MartinKleppmann曾经专门发文（<a target="_blank" rel="noopener" href="https://martin.kleppmann.com/2016/02/08/how-to-do-distributed-locking.html">Howtododistributedlocking-MartinKleppmann-2016</a>）怼过Redlock，他认为这是一个很差的分布式锁实现。感兴趣的朋友可以看看<a target="_blank" rel="noopener" href="https://mp.weixin.qq.com/s?__biz=Mzg3NjU3NTkwMQ==&mid=2247505097&idx=1&sn=5c03cb769c4458350f4d4a321ad51f5a&source=41#wechat_redirect">Redis锁从面试连环炮聊到神仙打架</a>这篇文章，有详细介绍到antirez和MartinKleppmann关于Redlock的激烈辩论。实际项目中不建议使用Redlock算法，成本和收益不成正比。如果不是非要实现绝对可靠的分布式锁的话，其实单机版Redis就完全够了，实现简单，性能也非常高。如果你必须要实现一个绝对可靠的分布式锁的话，可以基于ZooKeeper来做，只是性能会差一些。</p>
<blockquote>
<p><a target="_blank" rel="noopener" href="https://mp.weixin.qq.com/s/2cFtKhPX1QZ-ZxnZarYJrA">图解Redis分布式锁</a></p>
</blockquote>
<h3 id="基于ZooKeeper实现分布式锁"><a href="#基于ZooKeeper实现分布式锁" class="headerlink" title="基于ZooKeeper实现分布式锁"></a>基于ZooKeeper实现分布式锁</h3><p>Redis实现分布式锁性能较高，ZooKeeper实现分布式锁可靠性更高。实际项目中，我们应该根据业务的具体需求来选择。</p>
<p><strong>如何基于ZooKeeper实现分布式锁？</strong></p>
<p>客户端连接zookeeper，并在&#x2F;lock下创建临时的且有序的子节点，第一个客户端对应的子节点为&#x2F;lock&#x2F;lock-0000000000，第二个为&#x2F;lock&#x2F;lock-0000000001，以此类推；客户端获取&#x2F;lock下的子节点列表，判断自己创建的子节点是否为当前子节点列表中序号最小的子节点，如果是则认为获得锁，否则监听刚好在自己之前一位的子节点删除消息，获得子节点变更通知后重复此步骤直至获得锁；执行业务代码；完成业务流程后，删除对应的子节点释放锁。ZooKeeper分布式锁是基于<strong>临时顺序节点和Watcher（事件监听器）</strong> 实现的。</p>
<p>获取锁：</p>
<ol>
<li>首先我们要有一个持久节点&#x2F;locks，客户端获取锁就是在locks下创建临时顺序节点。</li>
<li>假设客户端1创建了&#x2F;locks&#x2F;lock1节点，创建成功之后，会判断lock1是否是&#x2F;locks下最小的子节点。</li>
<li>如果lock1是最小的子节点，则获取锁成功。否则，获取锁失败。</li>
<li>如果获取锁失败，则说明有其他的客户端已经成功获取锁。客户端1并不会不停地循环去尝试加锁，而是在前一个节点比如&#x2F;locks&#x2F;lock0上注册一个事件监听器。这个监听器的作用是当前一个节点释放锁之后通知客户端1（避免无效自旋），这样客户端1就加锁成功了。</li>
</ol>
<p>释放锁：</p>
<ol>
<li>成功获取锁的客户端在执行完业务流程之后，会将对应的子节点删除。</li>
<li>成功获取锁的客户端在出现故障之后，对应的子节点由于是临时顺序节点，也会被自动删除，避免了锁无法被释放。</li>
<li>我们前面说的事件监听器其实监听的就是这个子节点删除事件，子节点删除就意味着锁被释放。</li>
</ol>
<p>实际项目中，推荐使用<strong>Curator</strong>来实现ZooKeeper分布式锁。<strong>Curator</strong>是Netflix公司开源的一套ZooKeeper Java客户端框架，相比于ZooKeeper自带的客户端zookeeper来说，Curator的封装更加完善，各种API都可以比较方便地使用。Curator主要实现了下面四种锁：</p>
<ul>
<li><strong>InterProcessMutex</strong>：分布式可重入排它锁</li>
<li><strong>InterProcessSemaphoreMutex</strong>：分布式不可重入排它锁</li>
<li><strong>InterProcessReadWriteLock</strong>：分布式读写锁</li>
<li><strong>InterProcessMultiLock</strong>：将多个锁作为单个实体管理的容器，获取锁的时候获取所有锁，释放锁也会释放所有锁资源（忽略释放失败的锁）。</li>
</ul>
<pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token class-name">CuratorFramework</span> client <span class="token operator">=</span> <span class="token class-name">ZKUtils</span><span class="token punctuation">.</span><span class="token function">getClient</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
client<span class="token punctuation">.</span><span class="token function">start</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token comment">// 分布式可重入排它锁</span>
<span class="token class-name">InterProcessLock</span> lock1 <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">InterProcessMutex</span><span class="token punctuation">(</span>client<span class="token punctuation">,</span> lockPath1<span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token comment">// 分布式不可重入排它锁</span>
<span class="token class-name">InterProcessLock</span> lock2 <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">InterProcessSemaphoreMutex</span><span class="token punctuation">(</span>client<span class="token punctuation">,</span> lockPath2<span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token comment">// 将多个锁作为一个整体</span>
<span class="token class-name">InterProcessMultiLock</span> lock <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">InterProcessMultiLock</span><span class="token punctuation">(</span><span class="token class-name">Arrays</span><span class="token punctuation">.</span><span class="token function">asList</span><span class="token punctuation">(</span>lock1<span class="token punctuation">,</span> lock2<span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

<span class="token keyword">if</span> <span class="token punctuation">(</span><span class="token operator">!</span>lock<span class="token punctuation">.</span><span class="token function">acquire</span><span class="token punctuation">(</span><span class="token number">10</span><span class="token punctuation">,</span> <span class="token class-name">TimeUnit</span><span class="token punctuation">.</span><span class="token constant">SECONDS</span><span class="token punctuation">)</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
  	<span class="token keyword">throw</span> <span class="token keyword">new</span> <span class="token class-name">IllegalStateException</span><span class="token punctuation">(</span><span class="token string">"不能获取多锁"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token punctuation">&#125;</span>
<span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span><span class="token string">"已获取多锁"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span><span class="token string">"是否有第一个锁: "</span> <span class="token operator">+</span> lock1<span class="token punctuation">.</span><span class="token function">isAcquiredInThisProcess</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span><span class="token string">"是否有第二个锁: "</span> <span class="token operator">+</span> lock2<span class="token punctuation">.</span><span class="token function">isAcquiredInThisProcess</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token keyword">try</span> <span class="token punctuation">&#123;</span>
    <span class="token comment">// 资源操作</span>
 	 		resource<span class="token punctuation">.</span><span class="token function">use</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span> 
<span class="token punctuation">&#125;</span> <span class="token keyword">finally</span> <span class="token punctuation">&#123;</span>
    <span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span><span class="token string">"释放多个锁"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    lock<span class="token punctuation">.</span><span class="token function">release</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span> 
<span class="token punctuation">&#125;</span>
<span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span><span class="token string">"是否有第一个锁: "</span> <span class="token operator">+</span> lock1<span class="token punctuation">.</span><span class="token function">isAcquiredInThisProcess</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span><span class="token string">"是否有第二个锁: "</span> <span class="token operator">+</span> lock2<span class="token punctuation">.</span><span class="token function">isAcquiredInThisProcess</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
client<span class="token punctuation">.</span><span class="token function">close</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<p><strong>为什么要用临时顺序节点？</strong></p>
<p>每个数据节点在ZooKeeper中被称为znode，它是ZooKeeper中数据的最小单元。我们通常是将znode分为4大类：</p>
<ul>
<li><strong>持久（PERSISTENT）节点</strong>：一旦创建就一直存在即使ZooKeeper集群宕机，直到将其删除。</li>
<li><strong>临时（EPHEMERAL）节点</strong>：临时节点的生命周期是与客户端会话（session）绑定的，会话消失则节点消失。并且，临时节点只能做叶子节点，不能创建子节点。</li>
<li><strong>持久顺序（PERSISTENT_SEQUENTIAL）节点</strong>：除了具有持久（PERSISTENT）节点的特性之外，子节点的名称还具有顺序性。比如<code>/node1/app0000000001</code>、<code>/node1/app0000000002</code>。</li>
<li><strong>临时顺序（EPHEMERAL_SEQUENTIAL）节点</strong>：除了具备临时（EPHEMERAL）节点的特性之外，子节点的名称还具有顺序性。</li>
</ul>
<p>可以看出，临时节点相比持久节点，最主要的是对会话失效的情况处理不一样，临时节点会话消失则对应的节点消失。这样的话，如果客户端发生异常导致没来得及释放锁也没关系，会话失效节点自动被删除，不会发生死锁的问题。</p>
<p>使用Redis实现分布式锁的时候，我们是通过过期时间来避免锁无法被释放导致死锁问题的，而ZooKeeper直接利用临时节点的特性即可。假设不适用顺序节点的话，所有尝试获取锁的客户端都会对持有锁的子节点加监听器。当该锁被释放之后，势必会造成所有尝试获取锁的客户端来争夺锁，这样对性能不友好。使用顺序节点之后，只需要监听前一个节点就好了，对性能更友好。</p>
<p><strong>为什么要设置对前一个节点的监听？</strong></p>
<blockquote>
<p>Watcher（事件监听器），是ZooKeeper中的一个很重要的特性。ZooKeeper允许用户在指定节点上注册一些Watcher，并且在一些特定事件触发的时候，ZooKeeper服务端会将事件通知到感兴趣的客户端上去，该机制是ZooKeeper实现分布式协调服务的重要特性。</p>
</blockquote>
<p>同一时间段内，可能会有很多客户端同时获取锁，但只有一个可以获取成功。如果获取锁失败，则说明有其他的客户端已经成功获取锁。获取锁失败的客户端并不会不停地循环去尝试加锁，而是在前一个节点注册一个事件监听器。这个事件监听器的作用是：当前一个节点对应的客户端释放锁之后（也就是前一个节点被删除之后，监听的是删除事件），通知获取锁失败的客户端（唤醒等待的线程，Java中的<code>wait/notifyAll</code>），让它尝试去获取锁，然后就成功获取锁了。</p>
<p><strong>如何实现可重入锁？</strong></p>
<p>这里以Curator的<code>InterProcessMutex</code>对可重入锁的实现来介绍（源码地址：<a target="_blank" rel="noopener" href="https://github.com/apache/curator/blob/master/curator-recipes/src/main/java/org/apache/curator/framework/recipes/locks/InterProcessMutex.java">InterProcessMutex.java</a>）。当我们调用<code>InterProcessMutex#acquire</code>方法获取锁的时候，会调用<code>InterProcessMutex#internalLock</code>方法。</p>
<pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token comment">// 获取可重入互斥锁，直到获取成功为止</span>
<span class="token annotation punctuation">@Override</span>
<span class="token keyword">public</span> <span class="token keyword">void</span> <span class="token function">acquire</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token keyword">throws</span> <span class="token class-name">Exception</span> <span class="token punctuation">&#123;</span>
  <span class="token keyword">if</span> <span class="token punctuation">(</span><span class="token operator">!</span><span class="token function">internalLock</span><span class="token punctuation">(</span><span class="token operator">-</span><span class="token number">1</span><span class="token punctuation">,</span> <span class="token keyword">null</span><span class="token punctuation">)</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
    <span class="token keyword">throw</span> <span class="token keyword">new</span> <span class="token class-name">IOException</span><span class="token punctuation">(</span><span class="token string">"Lost connection while trying to acquire lock: "</span> <span class="token operator">+</span> basePath<span class="token punctuation">)</span><span class="token punctuation">;</span>
  <span class="token punctuation">&#125;</span>
<span class="token punctuation">&#125;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<p><code>internalLock</code>方法会先获取当前请求锁的线程，然后从<code>threadData(ConcurrentMap&lt;Thread,LockData&gt;类型)</code>中获取当前线程对应的lockData。lockData包含锁的信息和加锁的次数，是实现可重入锁的关键。第一次获取锁的时候，lockData为null。获取锁成功之后，会将当前线程和对应的lockData放到threadData中</p>
<pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token keyword">private</span> <span class="token keyword">boolean</span> <span class="token function">internalLock</span><span class="token punctuation">(</span><span class="token keyword">long</span> time<span class="token punctuation">,</span> <span class="token class-name">TimeUnit</span> unit<span class="token punctuation">)</span> <span class="token keyword">throws</span> <span class="token class-name">Exception</span> <span class="token punctuation">&#123;</span>
  <span class="token comment">// 获取当前请求锁的线程</span>
  <span class="token class-name">Thread</span> currentThread <span class="token operator">=</span> <span class="token class-name">Thread</span><span class="token punctuation">.</span><span class="token function">currentThread</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
  <span class="token comment">// 拿对应的lockData</span>
  <span class="token class-name">LockData</span> lockData <span class="token operator">=</span> threadData<span class="token punctuation">.</span><span class="token function">get</span><span class="token punctuation">(</span>currentThread<span class="token punctuation">)</span><span class="token punctuation">;</span>
  <span class="token comment">// 第一次获取锁的话，lockData为null</span>
  <span class="token keyword">if</span> <span class="token punctuation">(</span>lockData <span class="token operator">!=</span> <span class="token keyword">null</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
    <span class="token comment">// 当前线程获取过一次锁之后</span>
    <span class="token comment">// 因为当前线程的锁存在，lockCount自增后返回，实现锁重入.</span>
    lockData<span class="token punctuation">.</span>lockCount<span class="token punctuation">.</span><span class="token function">incrementAndGet</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token keyword">return</span> <span class="token boolean">true</span><span class="token punctuation">;</span>
  <span class="token punctuation">&#125;</span>
  <span class="token comment">// 尝试获取锁</span>
  <span class="token class-name">String</span> lockPath <span class="token operator">=</span> internals<span class="token punctuation">.</span><span class="token function">attemptLock</span><span class="token punctuation">(</span>time<span class="token punctuation">,</span> unit<span class="token punctuation">,</span> <span class="token function">getLockNodeBytes</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
  <span class="token keyword">if</span> <span class="token punctuation">(</span>lockPath <span class="token operator">!=</span> <span class="token keyword">null</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
    <span class="token class-name">LockData</span> newLockData <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">LockData</span><span class="token punctuation">(</span>currentThread<span class="token punctuation">,</span> lockPath<span class="token punctuation">)</span><span class="token punctuation">;</span>
     <span class="token comment">// 获取锁成功之后，将当前线程和对应的lockData放到threadData中</span>
    threadData<span class="token punctuation">.</span><span class="token function">put</span><span class="token punctuation">(</span>currentThread<span class="token punctuation">,</span> newLockData<span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token keyword">return</span> <span class="token boolean">true</span><span class="token punctuation">;</span>
  <span class="token punctuation">&#125;</span>

  <span class="token keyword">return</span> <span class="token boolean">false</span><span class="token punctuation">;</span>
<span class="token punctuation">&#125;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<p>LockData是InterProcessMutex中的一个静态内部类。</p>
<pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token keyword">private</span> <span class="token keyword">final</span> <span class="token class-name">ConcurrentMap</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token class-name">Thread</span><span class="token punctuation">,</span> <span class="token class-name">LockData</span><span class="token punctuation">></span></span> threadData <span class="token operator">=</span> <span class="token class-name">Maps</span><span class="token punctuation">.</span><span class="token function">newConcurrentMap</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

<span class="token keyword">private</span> <span class="token keyword">static</span> <span class="token keyword">class</span> <span class="token class-name">LockData</span>
<span class="token punctuation">&#123;</span>
    <span class="token comment">// 当前持有锁的线程</span>
    <span class="token keyword">final</span> <span class="token class-name">Thread</span> owningThread<span class="token punctuation">;</span>
    <span class="token comment">// 锁对应的子节点</span>
    <span class="token keyword">final</span> <span class="token class-name">String</span> lockPath<span class="token punctuation">;</span>
    <span class="token comment">// 加锁的次数</span>
    <span class="token keyword">final</span> <span class="token class-name">AtomicInteger</span> lockCount <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">AtomicInteger</span><span class="token punctuation">(</span><span class="token number">1</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

    <span class="token keyword">private</span> <span class="token class-name">LockData</span><span class="token punctuation">(</span><span class="token class-name">Thread</span> owningThread<span class="token punctuation">,</span> <span class="token class-name">String</span> lockPath<span class="token punctuation">)</span>
    <span class="token punctuation">&#123;</span>
      <span class="token keyword">this</span><span class="token punctuation">.</span>owningThread <span class="token operator">=</span> owningThread<span class="token punctuation">;</span>
      <span class="token keyword">this</span><span class="token punctuation">.</span>lockPath <span class="token operator">=</span> lockPath<span class="token punctuation">;</span>
    <span class="token punctuation">&#125;</span>
<span class="token punctuation">&#125;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<p>如果已经获取过一次锁，后面再来获取锁的话，直接就会在<code>if (lockData != null)</code>这里被拦下了，然后就会执行<code>lockData.lockCount.incrementAndGet();</code>将加锁次数加 1。整个可重入锁的实现逻辑非常简单，直接在客户端判断当前线程有没有获取锁，有的话直接将加锁次数加1就可以了。</p>
<h3 id="总结"><a href="#总结" class="headerlink" title="总结"></a>总结</h3><p>这篇文章我们介绍了分布式锁的基本概念以及实现分布式锁的两种常见方式。至于具体选择Redis还是ZooKeeper来实现分布式锁，还是要看业务的具体需求。如果对性能要求比较高的话，建议使用Redis实现分布式锁。如果对可靠性要求比较高的话，建议使用ZooKeeper实现分布式锁。</p>
<blockquote>
<p><a target="_blank" rel="noopener" href="https://javaguide.cn/distributed-system/distributed-lock.html">原文链接</a></p>
</blockquote>
<h3 id="相关文章"><a href="#相关文章" class="headerlink" title="相关文章"></a>相关文章</h3><table>
<thead>
<tr>
<th align="center"><a target="_blank" rel="noopener" href="https://mp.weixin.qq.com/s/Y7-cwHq1Z2hs2CWooFgVyg">关于分布式锁的面试题都在这里了</a></th>
<th align="center"><a target="_blank" rel="noopener" href="https://mp.weixin.qq.com/s/xKVdMvmNvy-1iV0tqx70Ng">分布式锁之Zookeeper</a></th>
<th align="center"><a target="_blank" rel="noopener" href="https://mp.weixin.qq.com/s/q1E5WnBKmoHZ59Euyk0kVw">电商防超卖的锁的解决方案</a></th>
</tr>
</thead>
<tbody><tr>
<td align="center"><a target="_blank" rel="noopener" href="https://mp.weixin.qq.com/s/5T0nrf5LBSqOiPd99OB3tw">阿里面试官：分布式锁到底用Redis好？还是Zookeeper好？</a></td>
<td align="center"><a target="_blank" rel="noopener" href="https://mp.weixin.qq.com/s/_P3zWS1QzPdQp10Jb1bSOA">分布式锁用Redis还是Zookeeper？</a></td>
<td align="center"><a target="_blank" rel="noopener" href="https://mp.weixin.qq.com/s/O9XZxwAcrCY-ninASw0I5Q">Redis分布式锁到底安全吗</a></td>
</tr>
<tr>
<td align="center"><a target="_blank" rel="noopener" href="https://mp.weixin.qq.com/s/9SPMfKpv4iF_9m2F9ZTa3A">Redis分布式锁深入探究</a></td>
<td align="center"><a target="_blank" rel="noopener" href="https://mp.weixin.qq.com/s/LTS3MKBU2FbRivXyQJcptA">七种方案！探讨Redis分布式锁的正确使用姿势</a></td>
<td align="center"><a target="_blank" rel="noopener" href="https://mp.weixin.qq.com/s/vnVyvTeKvT_ZfMHr5_7CNg">聊聊redis分布式锁的8大坑</a></td>
</tr>
<tr>
<td align="center"><a target="_blank" rel="noopener" href="https://mp.weixin.qq.com/s/yUH8jH9NTPLk24J_BQ0JfQ">这才叫细：带你深入理解Redis分布式锁</a></td>
<td align="center"><a target="_blank" rel="noopener" href="https://mp.weixin.qq.com/s/XnDxJgs9fp-zAGLZ5g2vsw">RedisTemplate分布式锁演变、Redission分布式锁实现</a></td>
<td align="center"><a target="_blank" rel="noopener" href="https://mp.weixin.qq.com/s/BlDsXWOcqpudORSiyI05Lg">年轻人，看看Redisson分布式锁—可重入锁吧！太重要了</a></td>
</tr>
<tr>
<td align="center"><a target="_blank" rel="noopener" href="https://mp.weixin.qq.com/s/PKGYoerpjWGeDzDE2iCFag">Redis分布式锁的正确实现原理演化历程与Redisson实战总结</a></td>
<td align="center"><a target="_blank" rel="noopener" href="https://mp.weixin.qq.com/s/fwpHS07LcLLe82_cGOUxKA">从零到一编码实现Redis分布式锁</a></td>
<td align="center"><a target="_blank" rel="noopener" href="https://mp.weixin.qq.com/s/x9YFF4QtHrCu3abSQHEL-A">面试官问：Redis分布式锁如何自动续期？</a></td>
</tr>
</tbody></table>
<h2 id="Java中的锁"><a href="#Java中的锁" class="headerlink" title="Java中的锁"></a>Java中的锁</h2><h3 id="synchronized"><a href="#synchronized" class="headerlink" title="synchronized"></a>synchronized</h3><p><strong>synchronized是什么？有什么用？</strong></p>
<p>synchronized是Java中的一个关键字，翻译成中文是同步的意思，主要解决的是多个线程之间访问资源的同步性，可以保证被它修饰的方法或者代码块在任意时刻只能有一个线程执行。在Java早期版本中，synchronized属于重量级锁，效率低下。这是因为监视器锁（monitor）是依赖于底层的操作系统的Mutex Lock来实现的，Java的线程是映射到操作系统的原生线程之上的。如果要挂起或者唤醒一个线程，都需要操作系统帮忙完成，而操作系统实现线程之间的切换时需要从用户态转换到内核态，这个状态之间的转换需要相对比较长的时间，时间成本相对较高。不过，在Java6之后，synchronized引入了大量的优化如自旋锁、适应性自旋锁、锁消除、锁粗化、偏向锁、轻量级锁等技术来减少锁操作的开销，这些优化让synchronized锁的效率提升了很多。因此，synchronized还是可以在实际项目中使用的，像JDK源码、很多开源框架都大量使用了synchronized。</p>
<p><strong>如何使用synchronized？</strong></p>
<p>synchronized关键字的使用方式主要有下面3种：</p>
<ol>
<li><strong>修饰实例方法</strong></li>
<li><strong>修饰静态方法</strong></li>
<li><strong>修饰代码块</strong></li>
</ol>
<p><strong>1、修饰实例方法（锁当前对象实例）</strong></p>
<p>给当前对象实例加锁，进入同步代码前要获得当前对象实例的锁。</p>
<pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token keyword">synchronized</span> <span class="token keyword">void</span> <span class="token function">method</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
    <span class="token comment">//业务代码</span>
<span class="token punctuation">&#125;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span></span></code></pre>

<p><strong>2、修饰静态方法（锁当前类）</strong></p>
<p>给当前类加锁，会作用于类的所有对象实例，进入同步代码前要获得当前class的锁。这是因为静态成员不属于任何一个实例对象，归整个类所有，不依赖于类的特定实例，被类的所有实例共享。</p>
<pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token keyword">synchronized</span> <span class="token keyword">static</span> <span class="token keyword">void</span> <span class="token function">method</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
    <span class="token comment">//业务代码</span>
<span class="token punctuation">&#125;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span></span></code></pre>

<p>静态synchronized方法和非静态synchronized方法之间的调用互斥么？不互斥！如果一个线程A调用一个实例对象的非静态synchronized方法，而线程B需要调用这个实例对象所属类的静态synchronized方法，是允许的，不会发生互斥现象，因为<strong>访问静态synchronized方法占用的锁是当前类的锁，而访问非静态synchronized方法占用的锁是当前实例对象锁</strong>。</p>
<p><strong>3、修饰代码块（锁指定对象&#x2F;类）</strong></p>
<p>对括号里指定的对象&#x2F;类加锁：</p>
<ul>
<li>synchronized(object)表示进入同步代码库前要获得给定对象的锁。</li>
<li>synchronized(类.class)表示进入同步代码前要获得给定Class的锁。</li>
</ul>
<pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token keyword">synchronized</span><span class="token punctuation">(</span><span class="token keyword">this</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
    <span class="token comment">//业务代码</span>
<span class="token punctuation">&#125;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span></span></code></pre>

<p>总结</p>
<ul>
<li>synchronized关键字加到static静态方法和synchronized(class)代码块上都是是给Class类上锁；</li>
<li>synchronized关键字加到实例方法上是给对象实例上锁；</li>
<li>尽量不要使用synchronized(String a)因为JVM中，字符串常量池具有缓存功能。</li>
</ul>
<p><strong>构造方法可以用synchronized修饰么？(不能)</strong></p>
<p>先说结论：构造方法不能使用synchronized关键字修饰。构造方法本身就属于线程安全的，不存在同步的构造方法一说。</p>
<p><strong>synchronized底层原理了解吗？</strong></p>
<p>synchronized关键字底层原理属于JVM层面的东西。</p>
<p><strong>synchronized同步语句块的情况</strong></p>
<pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token keyword">public</span> <span class="token keyword">class</span> <span class="token class-name">SynchronizedDemo</span> <span class="token punctuation">&#123;</span>
    <span class="token keyword">public</span> <span class="token keyword">void</span> <span class="token function">method</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
        <span class="token keyword">synchronized</span> <span class="token punctuation">(</span><span class="token keyword">this</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
            <span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span><span class="token string">"synchronized代码块"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token punctuation">&#125;</span>
    <span class="token punctuation">&#125;</span>
<span class="token punctuation">&#125;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<p>通过JDK自带的<code>javap</code>命令查看<code>SynchronizedDemo</code>类的相关字节码信息：首先切换到类的对应目录执行<code>javac SynchronizedDemo.java</code>命令生成编译后的.class文件，然后执行<code>javap -c -s -v -l SynchronizedDemo.class</code>。</p>
<p><img src="https://my-blog-to-use.oss-cn-beijing.aliyuncs.com/2019-6/synchronized%E5%85%B3%E9%94%AE%E5%AD%97%E5%8E%9F%E7%90%86.png" alt="synchronized关键字原理"></p>
<p>从上面我们可以看出：synchronized同步语句块的实现使用的是monitorenter和monitorexit指令，其中monitorenter指令指向同步代码块的开始位置，monitorexit指令则指明同步代码块的结束位置。当执行monitorenter指令时，线程试图获取锁也就是获取对象监视器monitor的持有权。</p>
<blockquote>
<p>在Java虚拟机(HotSpot)中，Monitor是基于C++实现的，由<a target="_blank" rel="noopener" href="https://github.com/openjdk-mirror/jdk7u-hotspot/blob/50bdefc3afe944ca74c3093e7448d6b889cd20d1/src/share/vm/runtime/objectMonitor.cpp">ObjectMonitor</a>实现的。每个对象中都内置了一个ObjectMonitor对象。</p>
<p>另外，wait&#x2F;notify等方法也依赖于monitor对象，这就是为什么只有在同步的块或者方法中才能调用wait&#x2F;notify等方法，否则会抛出java.lang.IllegalMonitorStateException的异常的原因。</p>
</blockquote>
<p>在执行monitorenter时，会尝试获取对象的锁，如果锁的计数器为0则表示锁可以被获取，获取后将锁计数器设为1也就是加1。</p>
<p><img src="https://guide-blog-images.oss-cn-shenzhen.aliyuncs.com/github/javaguide/java/concurrent/synchronized-get-lock-code-block.png" alt="执行monitorenter获取锁"></p>
<p>对象锁的的拥有者线程才可以执行monitorexit指令来释放锁。在执行monitorexit指令后，将锁计数器设为0，表明锁被释放，其他线程可以尝试获取锁。</p>
<p><img src="https://guide-blog-images.oss-cn-shenzhen.aliyuncs.com/github/javaguide/java/concurrent/synchronized-release-lock-block.png" alt="执行monitorexit释放锁"></p>
<p>如果获取对象锁失败，那当前线程就要阻塞等待，直到锁被另外一个线程释放为止。</p>
<p><strong>synchronized修饰方法的的情况</strong></p>
<pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token keyword">public</span> <span class="token keyword">class</span> <span class="token class-name">SynchronizedDemo2</span> <span class="token punctuation">&#123;</span>
    <span class="token keyword">public</span> <span class="token keyword">synchronized</span> <span class="token keyword">void</span> <span class="token function">method</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
        <span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span><span class="token string">"synchronized方法"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token punctuation">&#125;</span>
<span class="token punctuation">&#125;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<p><img src="https://my-blog-to-use.oss-cn-beijing.aliyuncs.com/2019-6/synchronized%E5%85%B3%E9%94%AE%E5%AD%97%E5%8E%9F%E7%90%862.png" alt="synchronized关键字原理"></p>
<p>synchronized修饰的方法并没有monitorenter指令和monitorexit指令，取得代之的确实是ACC_SYNCHRONIZED标识，该标识指明了该方法是一个同步方法。JVM通过该ACC_SYNCHRONIZED访问标志来辨别一个方法是否声明为同步方法，从而执行相应的同步调用。</p>
<p>如果是实例方法，JVM会尝试获取实例对象的锁。如果是静态方法，JVM会尝试获取当前class的锁。</p>
<p><strong>总结</strong></p>
<p>synchronized同步语句块的实现使用的是monitorenter和monitorexit指令，其中monitorenter指令指向同步代码块的开始位置，monitorexit指令则指明同步代码块的结束位置。synchronized修饰的方法并没有monitorenter指令和monitorexit指令，取得代之的确实是ACC_SYNCHRONIZED标识，该标识指明了该方法是一个同步方法。<strong>不过两者的本质都是对对象监视器monitor的获取。</strong></p>
<blockquote>
<p>相关推荐：<a target="_blank" rel="noopener" href="https://tech.youzan.com/javasuo-yu-xian-cheng-de-na-xie-shi/">Java锁与线程的那些事</a><br>🧗🏻进阶一下：学有余力的小伙伴可以抽时间详细研究一下对象监视器monitor。</p>
</blockquote>
<p><strong>JDK1.6之后的synchronized底层做了哪些优化？</strong></p>
<p>JDK1.6对锁的实现引入了大量的优化，如偏向锁、轻量级锁、自旋锁、适应性自旋锁、锁消除、锁粗化等技术来减少锁操作的开销。锁主要存在四种状态，依次是：无锁状态、偏向锁状态、轻量级锁状态、重量级锁状态，他们会随着竞争的激烈而逐渐升级。注意锁可以升级不可降级，这种策略是为了提高获得锁和释放锁的效率。关于这几种优化的详细信息可以查看下面这篇文章：<a target="_blank" rel="noopener" href="https://www.cnblogs.com/wuqinglong/p/9945618.html">Java6及以上版本对synchronized的优化</a>。</p>
<p><strong>synchronized和volatile有什么区别？</strong></p>
<p><code>synchronized</code>关键字和<code>volatile</code>关键字是两个互补的存在，而不是对立的存在！</p>
<ul>
<li>volatile关键字是线程同步的轻量级实现，所以volatile性能肯定比synchronized关键字要好。但是volatile关键字只能用于变量而synchronized关键字可以修饰方法以及代码块。</li>
<li>volatile关键字能保证数据的可见性，但不能保证数据的原子性。synchronized关键字两者都能保证。</li>
<li>volatile关键字主要用于解决变量在多个线程之间的可见性，而synchronized关键字解决的是多个线程之间访问资源的同步性。</li>
</ul>
<blockquote>
<p><a target="_blank" rel="noopener" href="https://javaguide.cn/java/concurrent/java-concurrent-questions-02.html">原文链接</a></p>
</blockquote>
<h4 id="相关文章-1"><a href="#相关文章-1" class="headerlink" title="相关文章"></a>相关文章</h4><table>
<thead>
<tr>
<th align="center"><a target="_blank" rel="noopener" href="https://mp.weixin.qq.com/s/lt9pL7aMknGZwEHzWe6hCA">synchronized关键字和Lock、区别</a></th>
<th align="center"><a target="_blank" rel="noopener" href="https://mp.weixin.qq.com/s/LcykdAXYF3Oj3xTl221_rQ">Synchronized天天用，实现原理你懂吗？</a></th>
<th align="center"><a target="_blank" rel="noopener" href="https://mp.weixin.qq.com/s/clnJLeDbG0pxwd6EUewQwQ">关于Synchronized的一个点，网上99%的文章都错了</a></th>
</tr>
</thead>
<tbody><tr>
<td align="center"><a target="_blank" rel="noopener" href="https://mp.weixin.qq.com/s/zP1XnF_wvUD0HRS4cDCdVg">13张图，深入理解Synchronized</a></td>
<td align="center"><a target="_blank" rel="noopener" href="https://mp.weixin.qq.com/s/KmYoVfiCbr3y4HBQnzL1HQ">synchronized中的4个优化，你知道几个？</a></td>
<td align="center"><a target="_blank" rel="noopener" href="https://mp.weixin.qq.com/s/3elpJFnCb_fswt8tsNyu4g">使用了synchronized，为啥还有线程安全问题！？</a></td>
</tr>
<tr>
<td align="center"><a target="_blank" rel="noopener" href="https://mp.weixin.qq.com/s/ewXpaeMYNx7FAW_fYoQbPg">synchronized加锁this和class的区别</a></td>
<td align="center"><a target="_blank" rel="noopener" href="https://mp.weixin.qq.com/s/5wCL3LSpT44iMgVM9k9CaA">为什么wait方法要在synchronized中调用？</a></td>
<td align="center"><a target="_blank" rel="noopener" href="https://mp.weixin.qq.com/s/OSi1fEoGHA1qdC0dJMs55Q">synchronized底层了解一下…</a></td>
</tr>
<tr>
<td align="center"><a target="_blank" rel="noopener" href="https://mp.weixin.qq.com/s/Z6ZuE8oefnNHlNfCyQbohw">深入理解Synchronized</a></td>
<td align="center"><a target="_blank" rel="noopener" href="https://mp.weixin.qq.com/s/n8WxaUtkXkDOju5QkTASOQ">synchronized的8种用法,你会几种？</a></td>
<td align="center"><a target="_blank" rel="noopener" href="https://mp.weixin.qq.com/s/tM4mncQwIkt9zBR1W_dBcA">synchronized的用法,你知道多少？</a></td>
</tr>
<tr>
<td align="center"><a target="_blank" rel="noopener" href="https://mp.weixin.qq.com/s/LPKg5xq6xFSwnEAQo1-7-g">Synchronized的锁升级过程是什么样的</a></td>
<td align="center"></td>
<td align="center"></td>
</tr>
</tbody></table>
<h3 id="ReentrantLock"><a href="#ReentrantLock" class="headerlink" title="ReentrantLock"></a>ReentrantLock</h3><p><strong>ReentrantLock是什么？</strong></p>
<p>ReentrantLock实现了Lock接口，是一个可重入且独占式的锁，和synchronized关键字类似。不过，ReentrantLock更灵活、更强大，增加了轮询、超时、中断、公平锁和非公平锁等高级功能。</p>
<pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token keyword">public</span> <span class="token keyword">class</span> <span class="token class-name">ReentrantLock</span> <span class="token keyword">implements</span> <span class="token class-name">Lock</span><span class="token punctuation">,</span> <span class="token class-name"><span class="token namespace">java<span class="token punctuation">.</span>io<span class="token punctuation">.</span></span>Serializable</span> <span class="token punctuation">&#123;</span><span class="token punctuation">&#125;</span><span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre>

<p>ReentrantLock里面有一个内部类Sync，Sync继承AQS（AbstractQueuedSynchronizer），添加锁和释放锁的大部分操作实际上都是在Sync中实现的。Sync有公平锁FairSync和非公平锁NonfairSync两个子类。</p>
<p><img src="https://guide-blog-images.oss-cn-shenzhen.aliyuncs.com/github/javaguide/java/concurrent/reentrantlock-class-diagram.png" alt="img"></p>
<p>ReentrantLock默认使用非公平锁，也可以通过构造器来显示的指定使用公平锁。</p>
<pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token comment">// 传入一个boolean值，true时为公平锁，false时为非公平锁</span>
<span class="token keyword">public</span> <span class="token class-name">ReentrantLock</span><span class="token punctuation">(</span><span class="token keyword">boolean</span> fair<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
    sync <span class="token operator">=</span> fair <span class="token operator">?</span> <span class="token keyword">new</span> <span class="token class-name">FairSync</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator">:</span> <span class="token keyword">new</span> <span class="token class-name">NonfairSync</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token punctuation">&#125;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span></span></code></pre>

<p>从上面的内容可以看出，ReentrantLock的底层就是由AQS来实现的。关于AQS的相关内容推荐阅读<a target="_blank" rel="noopener" href="https://javaguide.cn/java/concurrent/aqs.html">AQS详解</a>这篇文章。</p>
<p><strong>公平锁和非公平锁有什么区别？</strong></p>
<ul>
<li><strong>公平锁</strong>:锁被释放之后，先申请的线程先得到锁。性能较差一些，因为公平锁为了保证时间上的绝对顺序，上下文切换更频繁。</li>
<li><strong>非公平锁</strong>：锁被释放之后，后申请的线程可能会先获取到锁，是随机或者按照其他优先级排序的。性能更好，但可能会导致某些线程永远无法获取到锁。</li>
</ul>
<p><strong>synchronized和ReentrantLock有什么区别？</strong></p>
<p><strong>1. 两者都是可重入锁</strong></p>
<p>可重入锁也叫递归锁，指的是线程可以再次获取自己的内部锁。比如一个线程获得了某个对象的锁，此时这个对象锁还没有释放，当其再次想要获取这个对象的锁的时候还是可以获取的，如果是不可重入锁的话，就会造成死锁。JDK提供的所有现成的Lock实现类，包括synchronized关键字锁都是可重入的。在下面的代码中，method1()和method2()都被synchronized关键字修饰，method1()调用了method2()。</p>
<pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token keyword">public</span> <span class="token keyword">class</span> <span class="token class-name">ReentrantLockDemo</span> <span class="token punctuation">&#123;</span>
    <span class="token keyword">public</span> <span class="token keyword">synchronized</span> <span class="token keyword">void</span> <span class="token function">method1</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
        <span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span><span class="token string">"方法1"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token function">method2</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token punctuation">&#125;</span>

    <span class="token keyword">public</span> <span class="token keyword">synchronized</span> <span class="token keyword">void</span> <span class="token function">method2</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
        <span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span><span class="token string">"方法2"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token punctuation">&#125;</span>
<span class="token punctuation">&#125;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<p>由于synchronized锁是可重入的，同一个线程在调用method1()时可以直接获得当前对象的锁，执行method2()的时候可以再次获取这个对象的锁，不会产生死锁问题。假如synchronized是不可重入锁的话，由于该对象的锁已被当前线程所持有且无法释放，这就导致线程在执行method2()时获取锁失败，会出现死锁问题。</p>
<p><strong>2. synchronized依赖于JVM而ReentrantLock依赖于API</strong></p>
<p>synchronized是依赖于JVM实现的，前面我们也讲到了虚拟机团队在JDK1.6为synchronized关键字进行了很多优化，但是这些优化都是在虚拟机层面实现的，并没有直接暴露给我们。</p>
<p>ReentrantLock是JDK层面实现的（也就是API层面，需要lock()和unlock()方法配合try&#x2F;finally语句块来完成），所以我们可以通过查看它的源代码，来看它是如何实现的。</p>
<p><strong>3. ReentrantLock比synchronized增加了一些高级功能</strong></p>
<p>相比synchronized，ReentrantLock增加了一些高级功能。主要来说主要有三点：</p>
<ul>
<li><strong>等待可中断</strong>:ReentrantLock提供了一种能够中断等待锁的线程的机制，通过lock.lockInterruptibly()来实现这个机制。也就是说正在等待的线程可以选择放弃等待，改为处理其他事情。</li>
<li><strong>可实现公平锁</strong>:ReentrantLock可以指定是公平锁还是非公平锁。而synchronized只能是非公平锁。所谓的公平锁就是先等待的线程先获得锁。ReentrantLock默认情况是非公平的，可以通过ReentrantLock类的ReentrantLock(boolean fair)构造方法来制定是否是公平的。</li>
<li><strong>可实现选择性通知（锁可以绑定多个条件）</strong>:synchronized关键字与wait()和notify()&#x2F;notifyAll()方法相结合可以实现等待&#x2F;通知机制。ReentrantLock类当然也可以实现，但是需要借助于Condition接口与newCondition()方法。</li>
</ul>
<p>如果你想使用上述功能，那么选择ReentrantLock是一个不错的选择。</p>
<p>关于Condition接口的补充：</p>
<blockquote>
<p>Condition是JDK1.5之后才有的，它具有很好的灵活性，比如可以实现多路通知功能也就是在一个Lock对象中可以创建多个Condition实例（即对象监视器），线程对象可以注册在指定的Condition中，从而可以有选择性的进行线程通知，在调度线程上更加灵活。在使用notify()&#x2F;notifyAll()方法进行通知时，被通知的线程是由JVM选择的，用ReentrantLock类结合Condition实例可以实现“选择性通知”，这个功能非常重要，而且是Condition接口默认提供的。而synchronized关键字就相当于整个Lock对象中只有一个Condition实例，所有的线程都注册在它一个身上。如果执行notifyAll()方法的话就会通知所有处于等待状态的线程，这样会造成很大的效率问题。而Condition实例的signalAll()方法，只会唤醒注册在该Condition实例中的所有等待线程。</p>
</blockquote>
<p><strong>可中断锁和不可中断锁有什么区别？</strong></p>
<ul>
<li><strong>可中断锁</strong>：获取锁的过程中可以被中断，不需要一直等到获取锁之后才能进行其他逻辑处理。ReentrantLock就属于是可中断锁。</li>
<li><strong>不可中断锁</strong>：一旦线程申请了锁，就只能等到拿到锁以后才能进行其他的逻辑处理。synchronized就属于是不可中断锁。</li>
</ul>
<blockquote>
<p><a target="_blank" rel="noopener" href="https://mp.weixin.qq.com/s/totowqfBABfFr95VKpppwQ">聊一聊ReentrantLock类的一些玩法</a><br><a target="_blank" rel="noopener" href="https://github.com/xmxe/demo/blob/master/study-demo/src/main/java/com/xmxe/jdkfeature/thread/juc/ReentrantLockTest.java">demo</a></p>
</blockquote>
<h4 id="ReentrantReadWriteLock"><a href="#ReentrantReadWriteLock" class="headerlink" title="ReentrantReadWriteLock"></a>ReentrantReadWriteLock</h4><p>ReentrantReadWriteLock在实际项目中使用的并不多，面试中也问的比较少，简单了解即可。JDK1.8引入了性能更好的读写锁StampedLock。</p>
<p><strong>ReentrantReadWriteLock是什么？</strong></p>
<p>ReentrantReadWriteLock实现了ReadWriteLock，是一个可重入的读写锁，既可以保证多个线程同时读的效率，同时又可以保证有写入操作时的线程安全。</p>
<pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token keyword">public</span> <span class="token keyword">class</span> <span class="token class-name">ReentrantReadWriteLock</span> <span class="token keyword">implements</span> <span class="token class-name">ReadWriteLock</span><span class="token punctuation">,</span> <span class="token class-name"><span class="token namespace">java<span class="token punctuation">.</span>io<span class="token punctuation">.</span></span>Serializable</span><span class="token punctuation">&#123;</span>
<span class="token punctuation">&#125;</span>
<span class="token keyword">public</span> <span class="token keyword">interface</span> <span class="token class-name">ReadWriteLock</span> <span class="token punctuation">&#123;</span>
    <span class="token class-name">Lock</span> <span class="token function">readLock</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token class-name">Lock</span> <span class="token function">writeLock</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token punctuation">&#125;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<ul>
<li>一般锁进行并发控制的规则：读读互斥、读写互斥、写写互斥。</li>
<li>读写锁进行并发控制的规则：读读不互斥、读写互斥、写写互斥（只有读读不互斥）。</li>
</ul>
<p>ReentrantReadWriteLock其实是两把锁，一把是WriteLock(写锁)，一把是ReadLock（读锁）。读锁是共享锁，写锁是独占锁。读锁可以被同时读，可以同时被多个线程持有，而写锁最多只能同时被一个线程持有。和ReentrantLock一样，ReentrantReadWriteLock底层也是基于AQS实现的。</p>
<p><img src="https://guide-blog-images.oss-cn-shenzhen.aliyuncs.com/github/javaguide/java/concurrent/reentrantreadwritelock-class-diagram.png" alt="img"></p>
<p>ReentrantReadWriteLock也支持公平锁和非公平锁，默认使用非公平锁，可以通过构造器来显示的指定。</p>
<pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token comment">// 传入一个boolean值，true时为公平锁，false时为非公平锁</span>
<span class="token keyword">public</span> <span class="token class-name">ReentrantReadWriteLock</span><span class="token punctuation">(</span><span class="token keyword">boolean</span> fair<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
    sync <span class="token operator">=</span> fair <span class="token operator">?</span> <span class="token keyword">new</span> <span class="token class-name">FairSync</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator">:</span> <span class="token keyword">new</span> <span class="token class-name">NonfairSync</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    readerLock <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">ReadLock</span><span class="token punctuation">(</span><span class="token keyword">this</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    writerLock <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">WriteLock</span><span class="token punctuation">(</span><span class="token keyword">this</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token punctuation">&#125;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<p><strong>ReentrantReadWriteLock适合什么场景？</strong></p>
<p>由于ReentrantReadWriteLock既可以保证多个线程同时读的效率，同时又可以保证有写入操作时的线程安全。因此，在读多写少的情况下，使用ReentrantReadWriteLock能够明显提升系统性能。</p>
<p><strong>共享锁和独占锁有什么区别？</strong></p>
<ul>
<li><strong>共享锁</strong>：一把锁可以被多个线程同时获得。</li>
<li><strong>独占锁</strong>：一把锁只能被一个线程获得。</li>
</ul>
<p><strong>线程持有读锁还能获取写锁吗？</strong></p>
<ul>
<li>在线程持有读锁的情况下，该线程不能取得写锁(因为获取写锁的时候，如果发现当前的读锁被占用，就马上获取失败，不管读锁是不是被当前线程持有)。</li>
<li>在线程持有写锁的情况下，该线程可以继续获取读锁（获取读锁时如果发现写锁被占用，只有写锁没有被当前线程占用的情况才会获取失败）。</li>
</ul>
<blockquote>
<p>读写锁的源码分析，推荐阅读<a target="_blank" rel="noopener" href="https://mp.weixin.qq.com/s/h3VIUyH9L0v14MrQJiiDbw">聊聊Java的几把JVM级锁</a>，写的很不错。</p>
</blockquote>
<p><strong>读锁为什么不能升级为写锁？</strong></p>
<p>写锁可以降级为读锁，但是读锁却不能升级为写锁。这是因为读锁升级为写锁会引起线程的争夺，毕竟写锁属于是独占锁，这样的话，会影响性能。另外，还可能会有死锁问题发生。举个例子：假设两个线程的读锁都想升级写锁，则需要对方都释放自己锁，而双方都不释放，就会产生死锁。</p>
<h4 id="StampedLock"><a href="#StampedLock" class="headerlink" title="StampedLock"></a>StampedLock</h4><p>StampedLock面试中问的比较少，不是很重要，简单了解即可。</p>
<p><strong>StampedLock是什么？</strong></p>
<p>StampedLock是JDK1.8引入的性能更好的读写锁，不可重入且不支持条件变量Conditon。不同于一般的Lock类，StampedLock并不是直接实现Lock或ReadWriteLock接口，而是基于CLH锁独立实现的（AQS也是基于这玩意）。</p>
<pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token keyword">public</span> <span class="token keyword">class</span> <span class="token class-name">StampedLock</span> <span class="token keyword">implements</span> <span class="token class-name"><span class="token namespace">java<span class="token punctuation">.</span>io<span class="token punctuation">.</span></span>Serializable</span> <span class="token punctuation">&#123;</span><span class="token punctuation">&#125;</span><span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre>

<p>StampedLock提供了三种模式的读写控制模式：读锁、写锁和乐观读。</p>
<ul>
<li><strong>写锁</strong>：独占锁，一把锁只能被一个线程获得。当一个线程获取写锁后，其他请求读锁和写锁的线程必须等待。类似于ReentrantReadWriteLock的写锁，不过这里的写锁是不可重入的。</li>
<li><strong>读锁</strong>（悲观读）：共享锁，没有线程获取写锁的情况下，多个线程可以同时持有读锁。如果己经有线程持有写锁，则其他线程请求获取该读锁会被阻塞。类似于ReentrantReadWriteLock的读锁，不过这里的读锁是不可重入的。</li>
<li><strong>乐观读</strong>：允许多个线程获取乐观读以及读锁。同时允许一个写线程获取写锁。</li>
</ul>
<p>另外，StampedLock还支持这三种锁在一定条件下进行相互转换。</p>
<pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token keyword">long</span> <span class="token function">tryConvertToWriteLock</span><span class="token punctuation">(</span><span class="token keyword">long</span> stamp<span class="token punctuation">)</span><span class="token punctuation">&#123;</span><span class="token punctuation">&#125;</span>
<span class="token keyword">long</span> <span class="token function">tryConvertToReadLock</span><span class="token punctuation">(</span><span class="token keyword">long</span> stamp<span class="token punctuation">)</span><span class="token punctuation">&#123;</span><span class="token punctuation">&#125;</span>
<span class="token keyword">long</span> <span class="token function">tryConvertToOptimisticRead</span><span class="token punctuation">(</span><span class="token keyword">long</span> stamp<span class="token punctuation">)</span><span class="token punctuation">&#123;</span><span class="token punctuation">&#125;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span></span></code></pre>

<p>StampedLock在获取锁的时候会返回一个long型的数据戳，该数据戳用于稍后的锁释放参数，如果返回的数据戳为0则表示锁获取失败。当前线程持有了锁再次获取锁还是会返回一个新的数据戳，这也是StampedLock不可重入的原因。</p>
<pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token comment">// 写锁</span>
<span class="token keyword">public</span> <span class="token keyword">long</span> <span class="token function">writeLock</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
    <span class="token keyword">long</span> s<span class="token punctuation">,</span> next<span class="token punctuation">;</span>  <span class="token comment">// bypass acquireWrite in fully unlocked case only</span>
    <span class="token keyword">return</span> <span class="token punctuation">(</span><span class="token punctuation">(</span><span class="token punctuation">(</span><span class="token punctuation">(</span>s <span class="token operator">=</span> state<span class="token punctuation">)</span> <span class="token operator">&amp;</span> <span class="token constant">ABITS</span><span class="token punctuation">)</span> <span class="token operator">==</span> <span class="token number">0L</span> <span class="token operator">&amp;&amp;</span>
             <span class="token class-name">U</span><span class="token punctuation">.</span><span class="token function">compareAndSwapLong</span><span class="token punctuation">(</span><span class="token keyword">this</span><span class="token punctuation">,</span> <span class="token constant">STATE</span><span class="token punctuation">,</span> s<span class="token punctuation">,</span> next <span class="token operator">=</span> s <span class="token operator">+</span> <span class="token constant">WBIT</span><span class="token punctuation">)</span><span class="token punctuation">)</span> <span class="token operator">?</span>
            next <span class="token operator">:</span> <span class="token function">acquireWrite</span><span class="token punctuation">(</span><span class="token boolean">false</span><span class="token punctuation">,</span> <span class="token number">0L</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token punctuation">&#125;</span>
<span class="token comment">// 读锁</span>
<span class="token keyword">public</span> <span class="token keyword">long</span> <span class="token function">readLock</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
    <span class="token keyword">long</span> s <span class="token operator">=</span> state<span class="token punctuation">,</span> next<span class="token punctuation">;</span>  <span class="token comment">// bypass acquireRead on common uncontended case</span>
    <span class="token keyword">return</span> <span class="token punctuation">(</span><span class="token punctuation">(</span>whead <span class="token operator">==</span> wtail <span class="token operator">&amp;&amp;</span> <span class="token punctuation">(</span>s <span class="token operator">&amp;</span> <span class="token constant">ABITS</span><span class="token punctuation">)</span> <span class="token operator">&lt;</span> <span class="token constant">RFULL</span> <span class="token operator">&amp;&amp;</span>
             <span class="token class-name">U</span><span class="token punctuation">.</span><span class="token function">compareAndSwapLong</span><span class="token punctuation">(</span><span class="token keyword">this</span><span class="token punctuation">,</span> <span class="token constant">STATE</span><span class="token punctuation">,</span> s<span class="token punctuation">,</span> next <span class="token operator">=</span> s <span class="token operator">+</span> <span class="token constant">RUNIT</span><span class="token punctuation">)</span><span class="token punctuation">)</span> <span class="token operator">?</span>
            next <span class="token operator">:</span> <span class="token function">acquireRead</span><span class="token punctuation">(</span><span class="token boolean">false</span><span class="token punctuation">,</span> <span class="token number">0L</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token punctuation">&#125;</span>
<span class="token comment">// 乐观读</span>
<span class="token keyword">public</span> <span class="token keyword">long</span> <span class="token function">tryOptimisticRead</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
    <span class="token keyword">long</span> s<span class="token punctuation">;</span>
    <span class="token keyword">return</span> <span class="token punctuation">(</span><span class="token punctuation">(</span><span class="token punctuation">(</span>s <span class="token operator">=</span> state<span class="token punctuation">)</span> <span class="token operator">&amp;</span> <span class="token constant">WBIT</span><span class="token punctuation">)</span> <span class="token operator">==</span> <span class="token number">0L</span><span class="token punctuation">)</span> <span class="token operator">?</span> <span class="token punctuation">(</span>s <span class="token operator">&amp;</span> <span class="token constant">SBITS</span><span class="token punctuation">)</span> <span class="token operator">:</span> <span class="token number">0L</span><span class="token punctuation">;</span>
<span class="token punctuation">&#125;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<p><strong>StampedLock的性能为什么更好？</strong></p>
<p>相比于传统读写锁多出来的乐观读是StampedLock比ReadWriteLock性能更好的关键原因。StampedLock的乐观读允许一个写线程获取写锁，所以不会导致所有写线程阻塞，也就是当读多写少的时候，写线程有机会获取写锁，减少了线程饥饿的问题，吞吐量大大提高。</p>
<p><strong>StampedLock适合什么场景？</strong></p>
<p>和ReentrantReadWriteLock一样，StampedLock同样适合读多写少的业务场景，可以作为ReentrantReadWriteLock的替代品，性能更好。不过，需要注意的是StampedLock不可重入，不支持条件变量Conditon，对中断操作支持也不友好（使用不当容易导致CPU飙升）。如果你需要用到ReentrantLock的一些高级性能，就不太建议使用StampedLock了。另外，StampedLock性能虽好，但使用起来相对比较麻烦，一旦使用不当，就会出现生产问题。强烈建议你在使用StampedLock之前，看看<a target="_blank" rel="noopener" href="https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/locks/StampedLock.html">StampedLock官方文档中的案例</a>。</p>
<p><strong>StampedLock的底层原理了解吗？</strong></p>
<p>StampedLock不是直接实现Lock或ReadWriteLock接口，而是基于CLH锁实现的（AQS也是基于这玩意），CLH锁是对自旋锁的一种改良，是一种隐式的链表队列。StampedLock通过CLH队列进行线程的管理，通过同步状态值state来表示锁的状态和类型。</p>
<p>StampedLock的原理和AQS原理比较类似，这里就不详细介绍了，感兴趣的可以看看下面这两篇文章：</p>
<blockquote>
<p><a target="_blank" rel="noopener" href="https://javaguide.cn/java/concurrent/aqs.html">AQS详解</a><br><a target="_blank" rel="noopener" href="https://segmentfault.com/a/1190000015808032">StampedLock底层原理分析</a></p>
<p><a target="_blank" rel="noopener" href="https://javaguide.cn/java/concurrent/java-concurrent-questions-02.html">原文链接</a></p>
</blockquote>
<h2 id="其他锁"><a href="#其他锁" class="headerlink" title="其他锁"></a>其他锁</h2><table>
<thead>
<tr>
<th align="center"><a target="_blank" rel="noopener" href="https://mp.weixin.qq.com/s/IxC46bZW99mjfdvIYyEqmg">聊聊13种锁的实现方式</a></th>
<th align="center"><a target="_blank" rel="noopener" href="https://mp.weixin.qq.com/s/ws0gp-cbbAteJ9kYg7d_-A">一文足以了解什么是Java中的锁</a></th>
<th align="center"><a target="_blank" rel="noopener" href="https://mp.weixin.qq.com/s/IfPkIxoTn5eqZExclaCUTA">图解Java中那18把锁</a></th>
</tr>
</thead>
<tbody><tr>
<td align="center"><a target="_blank" rel="noopener" href="https://mp.weixin.qq.com/s/M5WTYg_aGciaHma2X2hV-w">一文详解Java的几把JVM级锁</a></td>
<td align="center"><a target="_blank" rel="noopener" href="https://mp.weixin.qq.com/s/JbtY4Rf6NMqhmNY0RqkF2Q">一文图解带你了解Java中的那些锁！</a></td>
<td align="center"><a target="_blank" rel="noopener" href="https://mp.weixin.qq.com/s/rFYTWTwSVgwwhrn4ol0lPg">彻底说清楚JAVA锁的种类以及区别</a></td>
</tr>
<tr>
<td align="center"><a target="_blank" rel="noopener" href="https://mp.weixin.qq.com/s/bl4OWKUKPFD2VlcdArHBhQ">老大吩咐的可重入分布式锁，终于完美的实现了</a></td>
<td align="center"><a target="_blank" rel="noopener" href="https://mp.weixin.qq.com/s/09hgu1Z9DY2-zhksu4wFRQ">你用对锁了吗?浅谈Java”锁”事</a></td>
<td align="center"><a target="_blank" rel="noopener" href="https://mp.weixin.qq.com/s/HEylBNG8-uIHrUwDFE8GYA">一文看懂JUC之AQS机制</a></td>
</tr>
<tr>
<td align="center"><a target="_blank" rel="noopener" href="https://mp.weixin.qq.com/s/Gn0yyQiALJzD5nWRwMME8g">『图解Java并发』面试必问的CAS原理你会了吗？</a></td>
<td align="center"><a target="_blank" rel="noopener" href="https://mp.weixin.qq.com/s/x6h3xYaAdIPTnHxJTlb6cQ">了解这两个接口后，阿里多线程面试题秒AC</a></td>
<td align="center"><a target="_blank" rel="noopener" href="https://mp.weixin.qq.com/s/4mJIRUShBXcxmsR6otmuwQ">1.3w字，一文详解死锁！</a></td>
</tr>
<tr>
<td align="center"><a target="_blank" rel="noopener" href="https://mp.weixin.qq.com/s/9LX3G-99RnEY5dAY0KRGOw">重磅出击，20张图带你彻底了解ReentrantLock加锁解锁的原理</a></td>
<td align="center"><a target="_blank" rel="noopener" href="https://mp.weixin.qq.com/s/7j6eSX-p9TrySjCgbNeivw">一文掌握ReentrantLock加解锁原理</a></td>
<td align="center"><a target="_blank" rel="noopener" href="https://mp.weixin.qq.com/s/ft9GJlrL90mfY4Yz-6OhQA">什么是自旋锁？自旋的好处和后果是什么</a></td>
</tr>
<tr>
<td align="center"><a target="_blank" rel="noopener" href="https://mp.weixin.qq.com/s/YCI5cTxA1QPe16azDVQVMQ">被问到可重入锁条件队列，看这一篇就够了</a></td>
<td align="center"><a target="_blank" rel="noopener" href="https://mp.weixin.qq.com/s/KrTn6WQZOdcVfhCCEwGgPg">3分钟带你搞懂AQS原理设计</a></td>
<td align="center"><a target="_blank" rel="noopener" href="https://mp.weixin.qq.com/s/JwdhlkJh0rWkbD1BDk4-Hw">3分钟秒懂死锁产生原因！</a></td>
</tr>
</tbody></table>

                
            </div>
            <hr/>

            

    <div class="reprint" id="reprint-statement">
        
            <div class="reprint__author">
                <span class="reprint-meta" style="font-weight: bold;">
                    <i class="fas fa-user">
                        文章作者:
                    </i>
                </span>
                <span class="reprint-info">
                    <a href="/blog/about" rel="external nofollow noreferrer">xmxe</a>
                </span>
            </div>
            <div class="reprint__type">
                <span class="reprint-meta" style="font-weight: bold;">
                    <i class="fas fa-link">
                        文章链接:
                    </i>
                </span>
                <span class="reprint-info">
                    <a href="https://xmxe.github.io/blog/posts/35e64501a595/">https://xmxe.github.io/blog/posts/35e64501a595/</a>
                </span>
            </div>
            <div class="reprint__notice">
                <span class="reprint-meta" style="font-weight: bold;">
                    <i class="fas fa-copyright">
                        版权声明:
                    </i>
                </span>
                <span class="reprint-info">
                    本博客所有文章除特別声明外，均采用
                    <a href="https://creativecommons.org/licenses/by/4.0/deed.zh" rel="external nofollow noreferrer" target="_blank">CC BY 4.0</a>
                    许可协议。转载请注明来源
                    <a href="/blog/about" target="_blank">xmxe</a>
                    !
                </span>
            </div>
        
    </div>

    <script async defer>
      document.addEventListener("copy", function (e) {
        let toastHTML = '<span>复制成功，请遵循本文的转载规则</span><button class="btn-flat toast-action" onclick="navToReprintStatement()" style="font-size: smaller">查看</a>';
        M.toast({html: toastHTML})
      });

      function navToReprintStatement() {
        $("html, body").animate({scrollTop: $("#reprint-statement").offset().top - 80}, 800);
      }
    </script>



            <div class="tag_share" style="display: block;">
                <div class="post-meta__tag-list" style="display: inline-block;">
                    
                        <div class="article-tag">
                            <span class="chip bg-color">无标签</span>
                        </div>
                    
                </div>
                <div class="post_share" style="zoom: 80%; width: fit-content; display: inline-block; float: right; margin: -0.15rem 0;">
                    <link rel="stylesheet" type="text/css" href="/blog/libs/share/css/share.min.css">
<div id="article-share">

    
    <div class="social-share" data-sites="qq,qzone,wechat,weibo,douban" data-wechat-qrcode-helper="<p>微信扫一扫即可分享！</p>"></div>
    <script src="/blog/libs/share/js/social-share.min.js"></script>
    

    

</div>

                </div>
            </div>
            
                <style>
    #reward {
        margin: 40px 0;
        text-align: center;
    }

    #reward .reward-link {
        font-size: 1.4rem;
        line-height: 38px;
    }

    #reward .btn-floating:hover {
        box-shadow: 0 6px 12px rgba(0, 0, 0, 0.2), 0 5px 15px rgba(0, 0, 0, 0.2);
    }

    #rewardModal {
        width: 320px;
        height: 350px;
    }

    #rewardModal .reward-title {
        margin: 15px auto;
        padding-bottom: 5px;
    }

    #rewardModal .modal-content {
        padding: 10px;
    }

    #rewardModal .close {
        position: absolute;
        right: 15px;
        top: 15px;
        color: rgba(0, 0, 0, 0.5);
        font-size: 1.3rem;
        line-height: 20px;
        cursor: pointer;
    }

    #rewardModal .close:hover {
        color: #ef5350;
        transform: scale(1.3);
        -moz-transform:scale(1.3);
        -webkit-transform:scale(1.3);
        -o-transform:scale(1.3);
    }

    #rewardModal .reward-tabs {
        margin: 0 auto;
        width: 210px;
    }

    .reward-tabs .tabs {
        height: 38px;
        margin: 10px auto;
        padding-left: 0;
    }

    .reward-content ul {
        padding-left: 0 !important;
    }

    .reward-tabs .tabs .tab {
        height: 38px;
        line-height: 38px;
    }

    .reward-tabs .tab a {
        color: #fff;
        background-color: #ccc;
    }

    .reward-tabs .tab a:hover {
        background-color: #ccc;
        color: #fff;
    }

    .reward-tabs .wechat-tab .active {
        color: #fff !important;
        background-color: #22AB38 !important;
    }

    .reward-tabs .alipay-tab .active {
        color: #fff !important;
        background-color: #019FE8 !important;
    }

    .reward-tabs .reward-img {
        width: 210px;
        height: 210px;
    }
</style>

<div id="reward">
    <a href="#rewardModal" class="reward-link modal-trigger btn-floating btn-medium waves-effect waves-light red">赏</a>

    <!-- Modal Structure -->
    <div id="rewardModal" class="modal">
        <div class="modal-content">
            <a class="close modal-close"><i class="fas fa-times"></i></a>
            <h4 class="reward-title">你的赏识是我前进的动力</h4>
            <div class="reward-content">
                <div class="reward-tabs">
                    <ul class="tabs row">
                        <li class="tab col s6 alipay-tab waves-effect waves-light"><a href="#alipay">支付宝</a></li>
                        <li class="tab col s6 wechat-tab waves-effect waves-light"><a href="#wechat">微 信</a></li>
                    </ul>
                    <div id="alipay">
                        
                            <img src="/blog/medias/reward/alipay.jpg" class="reward-img" alt="支付宝打赏二维码">
                        
                    </div>
                    <div id="wechat">
                        
                            <img src="/blog/medias/reward/wechat.jpg" class="reward-img" alt="微信打赏二维码">
                        
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
    $(function () {
        $('.tabs').tabs();
    });
</script>

            
        </div>
    </div>

    

    

    

    

    

    

    

    

<article id="prenext-posts" class="prev-next articles">
    <div class="row article-row">
        
        <div class="article col s12 m6" data-aos="fade-up">
            <div class="article-badge left-badge text-color">
                <i class="fas fa-chevron-left"></i>&nbsp;上一篇</div>
            <div class="card">
                <a href="/blog/posts/442dc7ae24f1/">
                    <div class="card-image">
                        
                        <img src="https://img1.baidu.com/it/u=1369410832,3000356447&fm=253&fmt=auto&app=138&f=PNG?w=500&h=539" class="responsive-img" alt="消息队列-MQ">
                        
                        <span class="card-title">消息队列-MQ</span>
                    </div>
                </a>
                <div class="card-content article-content">
                    <div class="summary block-with-text">
                        
                            什么是消息队列我们可以把消息队列看作是一个存放消息的容器，当我们需要使用消息的时候，直接从容器中取出消息供自己使用即可。由于队列Queue是一种先进先出的数据结构，所以消费消息时也是按照顺序来消费的。

参与消息传递的双方称为生产者和消费者
                        

                    </div>
                    <div class="publish-info">
                        <span class="publish-date">
                            <!--
                            <i class="far fa-clock fa-fw icon-date"></i>2022-09-29
                            -->

                            
                                <i class="fas fa-user fa-fw"></i>
                                <a href="/blog/about" >
                                    xmxe
                                </a>
                            
                        </span>
                        <span class="publish-author">
                            
                                <i class="fas fa-bookmark fa-fw icon-category"></i>
                                
                                    <a href="/blog/categories/%E6%8A%80%E6%9C%AF%E6%A0%88/" class="post-category">
                                        技术栈
                                    </a>
                                
                            

                        </span>
                    </div>
                </div>
                
            </div>
        </div>
        
        
        <div class="article col s12 m6" data-aos="fade-up">
            <div class="article-badge right-badge text-color">
                下一篇&nbsp;<i class="fas fa-chevron-right"></i>
            </div>
            <div class="card">
                <a href="/blog/posts/75fb1533e3f4/">
                    <div class="card-image">
                        
                        <img src="https://pic2.zhimg.com/v2-1858f3d5d46af69688092c4c0a10285a_1440w.jpg" class="responsive-img" alt="Java中的volatile关键字">
                        
                        <span class="card-title">Java中的volatile关键字</span>
                    </div>
                </a>
                <div class="card-content article-content">
                    <div class="summary block-with-text">
                        
                            
VolatileTest.java

如何保证变量的可见性？在Java中，volatile关键字可以保证变量的可见性，如果我们将变量声明为volatile，这就指示JVM，这个变量是共享且不稳定的，每次使用它都到主存中进行读取。


vo
                        
                        
                    </div>
                    <div class="publish-info">
                        <span class="publish-date">
                            <!--
                            <i class="far fa-clock fa-fw icon-date"></i>2022-09-29
                            -->
                            
                                <i class="fas fa-user fa-fw"></i>
                                <a href="/blog/about" >
                                    xmxe
                                </a>
                            
                        </span>
                        <span class="publish-author">
                            
                                <i class="fas fa-bookmark fa-fw icon-category"></i>
                                
                                    <a href="/blog/categories/Java/" class="post-category">
                                        Java
                                    </a>
                                
                            
                        </span>
                    </div>
                </div>
                
            </div>
        </div>
        
    </div>
</article>

</div>



<!-- 代码块功能依赖 -->
<script type="text/javascript" src="/blog/libs/codeBlock/codeBlockFuction.js"></script>

<!-- 代码语言 -->

<script type="text/javascript" src="/blog/libs/codeBlock/codeLang.js"></script>


<!-- 代码块复制 -->

<script type="text/javascript" src="/blog/libs/codeBlock/codeCopy.js"></script>


<!-- 代码块收缩 -->

<script type="text/javascript" src="/blog/libs/codeBlock/codeShrink.js"></script>


    </div>
    <div id="toc-aside" class="expanded col l3 hide-on-med-and-down">
        <div class="toc-widget card">
            <div class="toc-title"><i class="far fa-list-alt"></i>&nbsp;&nbsp;目录</div>
            <div id="toc-content"></div>
        </div>
    </div>
</div>

<!-- TOC 悬浮按钮. -->

<div id="floating-toc-btn" class="hide-on-med-and-down">
    <a class="btn-floating btn-large bg-color">
        <i class="fas fa-list-ul"></i>
    </a>
</div>


<script src="/blog/libs/tocbot/tocbot.min.js"></script>
<script>
    $(function () {
        tocbot.init({
            tocSelector: '#toc-content',
            contentSelector: '#articleContent',
            headingsOffset: -($(window).height() * 0.4 - 45),
            collapseDepth: Number('0'),
            headingSelector: 'h1, h2, h3, h4, h5, h6'
        });

        // modify the toc link href to support Chinese.
        let i = 0;
        let tocHeading = 'toc-heading-';
        $('#toc-content a').each(function () {
            $(this).attr('href', '#' + tocHeading + (++i));
        });

        // modify the heading title id to support Chinese.
        i = 0;
        $('#articleContent').children('h1, h2, h3, h4, h5, h6').each(function () {
            $(this).attr('id', tocHeading + (++i));
        });

        // Set scroll toc fixed.
        let tocHeight = parseInt($(window).height() * 0.4 - 64);
        let $tocWidget = $('.toc-widget');
        $(window).scroll(function () {
            let scroll = $(window).scrollTop();
            /* add post toc fixed. */
            if (scroll > tocHeight) {
                $tocWidget.addClass('toc-fixed');
            } else {
                $tocWidget.removeClass('toc-fixed');
            }
        });

        
        /* 修复文章卡片 div 的宽度. */
        let fixPostCardWidth = function (srcId, targetId) {
            let srcDiv = $('#' + srcId);
            if (srcDiv.length === 0) {
                return;
            }

            let w = srcDiv.width();
            if (w >= 450) {
                w = w + 21;
            } else if (w >= 350 && w < 450) {
                w = w + 18;
            } else if (w >= 300 && w < 350) {
                w = w + 16;
            } else {
                w = w + 14;
            }
            $('#' + targetId).width(w);
        };

        // 切换TOC目录展开收缩的相关操作.
        const expandedClass = 'expanded';
        let $tocAside = $('#toc-aside');
        let $mainContent = $('#main-content');
        $('#floating-toc-btn .btn-floating').click(function () {
            if ($tocAside.hasClass(expandedClass)) {
                $tocAside.removeClass(expandedClass).hide();
                $mainContent.removeClass('l9');
            } else {
                $tocAside.addClass(expandedClass).show();
                $mainContent.addClass('l9');
            }
            fixPostCardWidth('artDetail', 'prenext-posts');
        });
        
    });
</script>

    

</main>




    <footer class="page-footer bg-color">
    
        <link rel="stylesheet" href="/blog/libs/aplayer/APlayer.min.css">
<style>
    .aplayer .aplayer-lrc p {
        
        display: none;
        
        font-size: 12px;
        font-weight: 700;
        line-height: 16px !important;
    }

    .aplayer .aplayer-lrc p.aplayer-lrc-current {
        
        display: none;
        
        font-size: 15px;
        color: #42b983;
    }

    
    .aplayer.aplayer-fixed.aplayer-narrow .aplayer-body {
        left: -66px !important;
    }

    .aplayer.aplayer-fixed.aplayer-narrow .aplayer-body:hover {
        left: 0px !important;
    }

    
</style>
<div class="">
    
    <div class="row">
        <meting-js class="col l8 offset-l2 m10 offset-m1 s12"
                   server="netease"
                   type="song"
                   id="569200213"
                   fixed='true'
                   autoplay='false'
                   theme='#42b983'
                   loop='all'
                   order='random'
                   preload='auto'
                   volume='0.7'
                   list-folded='true'
        >
        </meting-js>
    </div>
</div>

<script src="/blog/libs/aplayer/APlayer.min.js"></script>
<!-- <script src="https://cdn.jsdelivr.net/npm/meting@2/dist/Meting.min.js"></script> -->

    
    <div class="container row center-align" style="margin-bottom: 0px !important;">
        <div class="col s12 m8 l8 copy-right">
            Copyright&nbsp;&copy;
            
            
                <span id="year">2022-2025
                </span>
            
            

            <a href="/blog/about" target="_blank">
                xmxe
            </a>
            |&nbsp;Powered by&nbsp;
            <a href="https://hexo.io/" target="_blank">Hexo</a>
            |&nbsp;Theme&nbsp;
            <a href="https://github.com/blinkfox/hexo-theme-matery" target="_blank">Matery</a>
            <br>

            
            
            
            
            
            

            
            <br>

            
            <br>

            
        </div>
        <div class="col s12 m4 l4 social-link2 ">
    <a href="https://github.com/xmxe" class="tooltipped" target="_blank" data-tooltip="GitHub" data-position="top" data-delay="50">
        <i class="fab fa-github"></i>
    </a>



    <a href="https://gitee.com/xmxe" class="tooltipped" target="_blank" data-tooltip="码云" data-position="top" data-delay="50">
        <svg width="19" height="19" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" style="position: relative; top: 2px; left: 0.5px;">
            <path d="M512 1024C230.4 1024 0 793.6 0 512S230.4 0 512 0s512 230.4 512 512-230.4 512-512 512z m259.2-569.6H480c-12.8 0-25.6 12.8-25.6 25.6v64c0 12.8 12.8 25.6 25.6 25.6h176c12.8 0 25.6 12.8 25.6 25.6v12.8c0 41.6-35.2 76.8-76.8 76.8h-240c-12.8 0-25.6-12.8-25.6-25.6V416c0-41.6 35.2-76.8 76.8-76.8h355.2c12.8 0 25.6-12.8 25.6-25.6v-64c0-12.8-12.8-25.6-25.6-25.6H416c-105.6 0-188.8 86.4-188.8 188.8V768c0 12.8 12.8 25.6 25.6 25.6h374.4c92.8 0 169.6-76.8 169.6-169.6v-144c0-12.8-12.8-25.6-25.6-25.6z" fill="#fff">
            </path>
        </svg>
    </a>

















    
        
          <a href="/blog/download" class="tooltipped" target="_blank" data-tooltip="下载" data-position="top" data-delay="50">
            <i class="fas fa-download"></i>
          </a>
        
    



    <style>
  .mobiledevice {
    display: none !important;
  }

  footer .wechat_qrcode {
    position: fixed;
  }

  /*微信二维码*/
  .wechat_qrcode {
    position: absolute;
    margin-left: 10px;
    bottom: 10px;
    background: url("/blog/medias/xcx.png");
    zoom:40%;
  }

  .wechat:hover .wechat_qrcode {
    width: 430px;
    height: 430px;
    animation: move 0.4s linear 1 normal;
  }

  @keyframes move {
    0% {
      transform: translate(100px, 0);
      opacity: 0;
    }
    50% {
      transform: translate(50px, 0);
      opacity: 0.5;
    }
    100% {
      transform: translate(0, 0);
      opacity: 1;
    }
  }

  @media only screen and (max-width: 601px) {
    .wechat {
      display: none !important;
    }
    .mobiledevice {
      display: inline-block !important;
    }
  }
</style>

<a href="javascript:;" class="wechat" data-position="top" data-delay="50">
  <i class="fab fa-weixin"></i>
  <img class="wechat_qrcode" />
</a>

<a
  href="javascript:;"
  class="tooltipped mobiledevice"
  data-tooltip="微信: 464817304"
  data-position="top"
  data-delay="50"
>
  <i class="fab fa-weixin"></i>
</a>

</div>
    </div>
</footer>

<div class="progress-bar"></div>


    <!-- 搜索遮罩框 -->
<div id="searchModal" class="modal">
    <div class="modal-content">
        <div class="search-header">
            <span class="title"><i class="fas fa-search"></i>&nbsp;&nbsp;搜索</span>
            <input type="search" id="searchInput" name="s" placeholder="请输入搜索的关键字"
                   class="search-input">
        </div>
        <div id="searchResult"></div>
    </div>
</div>

<script type="text/javascript">
$(function () {
    var searchFunc = function (path, search_id, content_id) {
        'use strict';
        $.ajax({
            url: path,
            dataType: "xml",
            success: function (xmlResponse) {
                // get the contents from search data
                var datas = $("entry", xmlResponse).map(function () {
                    return {
                        title: $("title", this).text(),
                        content: $("content", this).text(),
                        url: $("url", this).text()
                    };
                }).get();
                var $input = document.getElementById(search_id);
                var $resultContent = document.getElementById(content_id);
                $input.addEventListener('input', function () {
                    var str = '<ul class=\"search-result-list\">';
                    var keywords = this.value.trim().toLowerCase().split(/[\s\-]+/);
                    $resultContent.innerHTML = "";
                    if (this.value.trim().length <= 0) {
                        return;
                    }
                    // perform local searching
                    datas.forEach(function (data) {
                        var isMatch = true;
                        var data_title = data.title.trim().toLowerCase();
                        var data_content = data.content.trim().replace(/<[^>]+>/g, "").toLowerCase();
                        var data_url = data.url;
                        data_url = data_url.indexOf('/') === 0 ? data.url : '/' + data_url;
                        var index_title = -1;
                        var index_content = -1;
                        var first_occur = -1;
                        // only match artiles with not empty titles and contents
                        if (data_title !== '' && data_content !== '') {
                            keywords.forEach(function (keyword, i) {
                                index_title = data_title.indexOf(keyword);
                                index_content = data_content.indexOf(keyword);
                                if (index_title < 0 && index_content < 0) {
                                    isMatch = false;
                                } else {
                                    if (index_content < 0) {
                                        index_content = 0;
                                    }
                                    if (i === 0) {
                                        first_occur = index_content;
                                    }
                                }
                            });
                        }
                        // show search results
                        if (isMatch) {
                            str += "<li><a href='" + data_url + "' class='search-result-title'>" + data_title + "</a>";
                            var content = data.content.trim().replace(/<[^>]+>/g, "");
                            if (first_occur >= 0) {
                                // cut out 100 characters
                                var start = first_occur - 20;
                                var end = first_occur + 80;
                                if (start < 0) {
                                    start = 0;
                                }
                                if (start === 0) {
                                    end = 100;
                                }
                                if (end > content.length) {
                                    end = content.length;
                                }
                                var match_content = content.substr(start, end);
                                // highlight all keywords
                                keywords.forEach(function (keyword) {
                                    var regS = new RegExp(keyword, "gi");
                                    match_content = match_content.replace(regS, "<em class=\"search-keyword\">" + keyword + "</em>");
                                });

                                str += "<p class=\"search-result\">" + match_content + "...</p>"
                            }
                            str += "</li>";
                        }
                    });
                    str += "</ul>";
                    $resultContent.innerHTML = str;
                });
            }
        });
    };

    searchFunc('/blog/search.xml', 'searchInput', 'searchResult');
});
</script>

    <!-- 回到顶部按钮 -->
<div id="backTop" class="top-scroll">
    <a class="btn-floating btn-large waves-effect waves-light" href="#!">
        <i class="fas fa-arrow-up"></i>
    </a>
</div>

    <div class="stars-con">
  <div id="stars"></div>
  <div id="stars2"></div>
  <div id="stars3"></div>  
</div>

<!-- 白天和黑夜主题 -->



<script>
  function switchNightMode() {
    
      setTimeout(function () {
        $('body').hasClass('DarkMode') 
        ? ($('body').removeClass('DarkMode'), localStorage.setItem('isDark', '0'), $('#sum-moon-icon').removeClass("fa-sun").addClass('fa-moon')) 
        : ($('body').addClass('DarkMode'), localStorage.setItem('isDark', '1'), $('#sum-moon-icon').addClass("fa-sun").removeClass('fa-moon')),
          
        setTimeout(function () {
          $('.Cuteen_DarkSky').fadeOut(1e3, function () {
            $(this).remove()
          })
        }, 2e3)
      })
  }
</script>
    
    
    <script>
        /* 模式判断 */
        if (localStorage.getItem('isDark') === '1') {
            document.body.classList.add('DarkMode');
            $('#sum-moon-icon').addClass("fa-sun").removeClass('fa-moon')
        } else {
            document.body.classList.remove('DarkMode');
            $('#sum-moon-icon').removeClass("fa-sun").addClass('fa-moon')
        }
    </script>

    <script src="/blog/libs/materialize/materialize.min.js"></script>
    <script src="/blog/libs/masonry/masonry.pkgd.min.js"></script>
    <script src="/blog/libs/aos/aos.js"></script>
    <script src="/blog/libs/scrollprogress/scrollProgress.min.js"></script>
    <script src="/blog/libs/lightGallery/js/lightgallery-all.min.js"></script>
    <script src="/blog/js/matery.js"></script>

    <!-- Baidu Analytics -->

    <!-- Baidu Push -->

<script>
    (function () {
        var bp = document.createElement('script');
        var curProtocol = window.location.protocol.split(':')[0];
        if (curProtocol === 'https') {
            bp.src = 'https://zz.bdstatic.com/linksubmit/push.js';
        } else {
            bp.src = 'http://push.zhanzhang.baidu.com/push.js';
        }
        var s = document.getElementsByTagName("script")[0];
        s.parentNode.insertBefore(bp, s);
    })();
</script>

    
    

    

    

	
    

    

    
    <script type="text/javascript" src="/blog/libs/background/ribbon-dynamic.js" async="async"></script>
    

    

    <!-- 冒泡 -->
    
    <script type="text/javascript">
        // 只在桌面版网页启用特效
        // var windowWidth = $(window).width();
        
            document.write('<script type="text/javascript" src="/blog/libs/others/bubleAll.js"><\/script>');
        
        
    </script>
    

    <!-- 弹出文字 -->
    

</body>

</html>
